PHPackages                             richarddobron/dom-forge - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Parsing &amp; Serialization](/categories/parsing)
4. /
5. richarddobron/dom-forge

ActiveLibrary[Parsing &amp; Serialization](/categories/parsing)

richarddobron/dom-forge
=======================

Lightweight PHP library for parsing and manipulating HTML documents.

2.0.0(4mo ago)038MITPHPPHP ^7.1 || ^8.0CI passing

Since Jan 11Pushed 4mo agoCompare

[ Source](https://github.com/richardDobron/dom-forge)[ Packagist](https://packagist.org/packages/richarddobron/dom-forge)[ RSS](/packages/richarddobron-dom-forge/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (2)Dependencies (2)Versions (4)Used By (0)

 [![PHP HTML PARSER](./logo/logo.svg)](./logo/logo.svg)Lightweight PHP library for parsing and manipulating HTML documents.

📖 Requirements
--------------

[](#-requirements)

- PHP 7.0 or higher
- [Composer](https://getcomposer.org) is required for installation
- PHP Extensions: `iconv`, `ext-mbstring`

📦 Installation
--------------

[](#-installation)

Install the library using Composer:

```
$ composer require richarddobron/dom-forge
```

⚡️ Quick Start
--------------

[](#️-quick-start)

### Creating DomForge Instance

[](#creating-domforge-instance)

```
// Without configuration
$dom1 = DomForge::fromHtml('Hello World');
$dom2 = DomForge::fromFile('/path/to/file.html');

// With configuration
$config = (new Configuration())
    ->setLowercase(true)
    ->setRemoveLineBreaks(true)
    ->setTargetCharset('UTF-8');

$dom1 = DomForge::fromHtml('Content', $config);
$dom2 = DomForge::fromFile('/path/to/file.html', $config);
```

### Finding Elements

[](#finding-elements)

```
// Find all matching elements
$elements = $dom->find('div.container');

// Find first matching element
$element = $dom->findOne('p');

// Find by index (0-based)
$element = $dom->find('p', 0);

// Find with CSS selectors
$dom->find('#id');           // By ID
$dom->find('.class');        // By class
$dom->find('div p');         // Descendant
$dom->find('div > p');       // Direct child
$dom->find('div + p');       // Adjacent sibling
$dom->find('div, p');        // Multiple selectors
$dom->find('[attribute]');   // Has attribute
$dom->find('[attr=value]');  // Attribute equals
$dom->find('[attr^=val]');   // Attribute starts with
$dom->find('[attr$=val]');   // Attribute ends with
$dom->find('[attr*=val]');   // Attribute contains
```

### Getting Content

[](#getting-content)

```
$element = $dom->findOne('div');

// Get inner HTML (child elements as HTML string)
$inner = $element->innerHtml();

// Get outer HTML (including the element itself)
$outer = $element->outerHtml();

// Get text content (strips HTML tags)
$text = $element->textContent();

// Using magic properties
$inner = $element->innerHtml;
$outer = $element->outerHtml;
$text = $element->textContent;
```

### Setting Content

[](#setting-content)

```
$element = $dom->findOne('div');

// Set inner HTML
$element->innerHtml = 'New content';

// Set outer HTML (replaces the element)
$element->outerHtml = 'Replaced';
```

### Creating Elements

[](#creating-elements)

```
// Create an element
$span = $dom->createElement('span');
$span = $dom->createElement('span', 'Hello World');  // with content
$span = $dom->createElement('a', 'Click', ['href' => 'https://example.com', 'class' => 'btn']);

// Create a text node
$textNode = $dom->createTextNode('Hello World');

// Create a comment
$comment = $dom->createComment('This is a comment');
```

### DOM Manipulation

[](#dom-manipulation)

```
// Append a child element
$container = $dom->findOne('#container');
$newElement = $dom->createElement('p', 'New paragraph');
$container->appendChild($newElement);

// Remove a child element
$child = $container->firstChild();
$container->removeChild($child);

// Insert before another element
$ul = $dom->findOne('ul');
$newLi = $dom->createElement('li', 'First item');
$existingLi = $ul->firstChild();
$ul->insertBefore($newLi, $existingLi);

// Check if element has children
if ($container->hasChildren()) {
    // ...
}
```

### Working with Attributes

[](#working-with-attributes)

```
$element = $dom->findOne('a');

// Get attribute
$href = $element->getAttribute('href');

// Check if attribute exists
if ($element->hasAttribute('target')) {
    // ...
}

// Set attribute
$element->setAttribute('class', 'link');

// Get all attributes
$attrs = $element->getAttributes();

// Remove attribute
$element->removeAttribute('class');

// Magic property access
$href = $element->href;
$element->class = 'active';
```

### Node Type Checking

[](#node-type-checking)

```
$node = $dom->findOne('div');

$node->isElement();   // true for HTML elements
$node->isText();      // true for text nodes
$node->isComment();   // true for comment nodes
$node->isSelfClosing();  // true for self-closing tags (br, img, etc.)
$node->isNamespacedElement();  // true for elements like fbt:param
```

### Traversing Nodes

[](#traversing-nodes)

```
$element = $dom->findOne('ul');

// Get parent
$parent = $element->parent;

// Get children
$children = $element->children();         // All child nodes
$firstChild = $element->children(0);      // First child by index
$firstChild = $element->firstChild();     // First child
$lastChild = $element->lastChild();       // Last child

// Get siblings
$next = $element->nextSibling();          // Next sibling element
$prev = $element->previousSibling();      // Previous sibling element

// Get nodes (includes text nodes)
$nodes = $element->nodes;
```

### Lookup Methods

[](#lookup-methods)

```
// Get element by ID
$element = $dom->getElementById('myId');

// Get elements by ID (with index support)
$elements = $dom->getElementsById('myId');
$element = $dom->getElementsById('myId', 0);

// Get element by tag name
$element = $dom->getElementByTagName('div');

// Get elements by tag name
$elements = $dom->getElementsByTagName('p');
$element = $dom->getElementsByTagName('p', 0);
```

### Callbacks

[](#callbacks)

```
$dom = DomForge::fromHtml('Test');

// Set a callback that runs when getting outerHtml
$dom->setCallback(function ($node) {
    // Process each node
});

// Remove callback
$dom->removeCallback();
```

### Saving Output

[](#saving-output)

```
// Get HTML as string
$html = $dom->save();

// Save to file
$dom->save('/path/to/file.html');

// Or use __toString
$html = (string) $dom;
```

⚙️ Configuration Options
------------------------

[](#️-configuration-options)

You can customize the library with the following methods:

MethodDescriptionDefault`setTargetCharset(string $targetCharset)`Sets the target character set for the HTML content.`'UTF-8'``setLowercase(bool $lowercase)`Enables or disables converting tag and attribute names to lowercase.`true``setForceTagsClosed(bool $forceTagsClosed)`Enables or disables forcing all tags to be closed.`true``setRemoveLineBreaks(bool $removeLineBreaks)`Enables or disables stripping of `\r` and `\n` characters from the HTML content.`false``setDefaultBrText(string $defaultBrText)`Sets the default text to use for `` tags.`"\n"``setDefaultSpanText(string $defaultSpanText)`Sets the default text to use for `` tags.`''``setSelfClosingTags(array $selfClosingTags)`Sets the extra list of self-closing tags.`null`📅 Change Log
------------

[](#-change-log)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

🧪 Testing
---------

[](#-testing)

```
$ composer tests
```

🤝 Contributing
--------------

[](#-contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

⚖️ License
----------

[](#️-license)

This repository is MIT licensed, as found in the [LICENSE](LICENSE) file.

###  Health Score

35

—

LowBetter than 80% of packages

Maintenance77

Regular maintenance activity

Popularity7

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity41

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

3

Last Release

127d ago

Major Versions

1.0.0.x-dev → 2.0.02026-01-11

PHP version history (2 changes)1.0.0PHP ^7.0

2.0.0PHP ^7.1 || ^8.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/1ce70053083f807f4416f0bafe680691b66cd14f3c1bdf7b3df51b6f5b5cfdea?d=identicon)[dobron](/maintainers/dobron)

---

Top Contributors

[![richardDobron](https://avatars.githubusercontent.com/u/33115305?v=4)](https://github.com/richardDobron "richardDobron (4 commits)")

---

Tags

htmlhtml-parsermanupulationparsertraversing

###  Code Quality

TestsPHPUnit

Code StylePHP CS Fixer

### Embed Badge

![Health badge](/badges/richarddobron-dom-forge/health.svg)

```
[![Health](https://phpackages.com/badges/richarddobron-dom-forge/health.svg)](https://phpackages.com/packages/richarddobron-dom-forge)
```

###  Alternatives

[masterminds/html5

An HTML5 parser and serializer.

1.8k242.8M229](/packages/masterminds-html5)[sabberworm/php-css-parser

Parser for CSS Files written in PHP

1.8k191.2M65](/packages/sabberworm-php-css-parser)[jms/metadata

Class/method/property metadata management in PHP

1.8k152.8M88](/packages/jms-metadata)[jms/serializer-bundle

Allows you to easily serialize, and deserialize data of any complexity

1.8k89.3M627](/packages/jms-serializer-bundle)[hassankhan/config

Lightweight configuration file loader that supports PHP, INI, XML, JSON, and YAML files

97513.5M170](/packages/hassankhan-config)[meyfa/php-svg

Read, edit, write, and render SVG files with PHP

54613.9M42](/packages/meyfa-php-svg)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
