PHPackages                             dlindberg/dom-document-factory - 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. [Utility &amp; Helpers](/categories/utility)
4. /
5. dlindberg/dom-document-factory

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

dlindberg/dom-document-factory
==============================

Simple DOMDocument factory with html purify and string output

1.0.0(7y ago)0201MITPHPPHP ^7.2CI failing

Since Mar 13Pushed 7y ago1 watchersCompare

[ Source](https://github.com/dlindberg/DOMDocumentFactory)[ Packagist](https://packagist.org/packages/dlindberg/dom-document-factory)[ Docs](https://github.com/dlindberg/DOMDocumentFactory)[ RSS](/packages/dlindberg-dom-document-factory/feed)WikiDiscussions master Synced today

READMEChangelog (1)Dependencies (3)Versions (3)Used By (1)

DOCFactory
==========

[](#docfactory)

[![Latest Version on Packagist](https://camo.githubusercontent.com/7e326e0227494d837baec7ca437923ad4a5e8dabc05cc4a4d42d0fde1a214acb/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f646c696e64626572672f646f6d2d646f63756d656e742d666163746f72792e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/dlindberg/dom-document-factory)[![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE.md)[![Build Status](https://camo.githubusercontent.com/739f86da904b290d47b3625e1fe3f37c2be994fcb45a6cbbee9c417f481b1778/68747470733a2f2f696d672e736869656c64732e696f2f7472617669732f646c696e64626572672f444f4d446f63756d656e74466163746f72792f6d61737465722e7376673f7374796c653d666c61742d737175617265)](https://travis-ci.org/dlindberg/DOMDocumentFactory)[![Coverage Status](https://camo.githubusercontent.com/ea6d4d94ad70582c98b11396e507eb159ed545ed7e9af6ce61816664eb779dde/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f636f7665726167652f672f646c696e64626572672f444f4d446f63756d656e74466163746f72792e7376673f7374796c653d666c61742d737175617265)](https://scrutinizer-ci.com/g/dlindberg/DOMDocumentFactory/code-structure)[![Quality Score](https://camo.githubusercontent.com/47626136157484a4e2bf9abd7cbe959035a6e633202f1fe1808126372c3087ef/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f672f646c696e64626572672f444f4d446f63756d656e74466163746f72792e7376673f7374796c653d666c61742d737175617265)](https://scrutinizer-ci.com/g/dlindberg/DOMDocumentFactory)[![Total Downloads](https://camo.githubusercontent.com/be54d6d3f663c9d9fe476a9a0282acc0ab42a688be7722b8021e7160eb7d42bc/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f646c696e64626572672f646f6d2d646f63756d656e742d666163746f72792e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/dlindberg/dom-document-factory)

The DOMDocument extension in PHP is very powerful and incredibly useful for manipulating HTML. However, there is just enough boilerplate code that having a little utility factory makes things just a little bit easier. I also find that what I frequently want to do is use HTMLPurifier to clean up some crufty HTML input, turn that into a DOMNode, manipulate it and then convert that back into a string. This is a simple factory to help with that workflow. It takes a string containing a fragment of HTML, purifies it, and turns it into a `` DOMNode. There is also a very little bit of boiler plate in getting that string back out, so this can handle that too—optionally with different pass of HTMLPurifier on the way out (not frequently necessary, but occasionally helpful).

This factory is setup so that you can simply initialize and invoke it and get back a DOMNode. Manipulate the DOM however you need to and then stringify your DOMNode back out. Of course defaults are good, but flexibility is important. So you can inject a DOCFactoryConfig to adjust the settings as needed—useful if you would need to implement a factory anyway because of your use case.

Install
-------

[](#install)

Via Composer

```
$ composer require dlindberg/DOMDocumentFactory
```

Usage
-----

[](#usage)

### Basic Invocation

[](#basic-invocation)

If all you really need to do is take a string of html and get a quickly usable DOMNode out of it, you can use the simply create an instance of the DOMDocumentFactory class and invoke it.

```
$html = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'; // Etc. Etc.

$docFactory = new dlindberg\DOMDocumentFactory();

$DOMNode = $docfactory($html);

/* Do something with your DOMNodes */

echo $docFactory->stringify($DOMNode->firstChild);
```

For an input of `This is some Text` if you made not further changes to your DOMNodes, the result would also be `this is some text`

Alternatively, there are two additional methods for invoking the factory. `getNode(string $blob)` and `getDocument(string $blob)`. The `getNode` method does the same thing that invoking the class does, and returns the `body` from the fragment. Using `getDocument` will return the entire `DOMDocument` class. Note that you can always get to the parent DOMDocument even when using the `getNode` method by using DOMDocument's [`ownerDocument`](https://secure.php.net/manual/en/class.domnode.php#domnode.props.ownerdocument) method.

If you have a section of HTML that has multiple immediate child nodes, for example:

```
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
In vel nibh eget turpis sagittis posuere ut vitae purus.
Donec in libero mauris. Aenean eu consectetur tortor.
Sed dolor neque, maximus et est eu, ultricies interdum libero.
Cras sed feugiat ante. Suspendisse ultrices eros at arcu feugiat dictum.
```

Simply using:

```
$DOMElement = $docfactory($html);
echo $docfactory->stringify($DOMElement->firstChild);
```

would result in:

```
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
```

And using:

```
echo $docfactory->stringify($DOMElement);
```

results in:

```

Lorem ipsum dolor sit amet, consectetur adipiscing elit.
In vel nibh eget turpis sagittis posuere ut vitae purus.
Donec in libero mauris. Aenean eu consectetur tortor.
Sed dolor neque, maximus et est eu, ultricies interdum libero.
Cras sed feugiat ante. Suspendisse ultrices eros at arcu feugiat dictum.

```

To get the same thing out that you put in you can use the `stringifyFromList` method. This returns an array of strings from each child node in a `NodeList`. If you need them as an array, you can simply use it as is. Or you can flatten the array using `implode`.

```
echo \implode(\PHP_EOL, $docfactory->stringifyFromList($DOMElement));
```

### Custom Invocation

[](#custom-invocation)

Sometimes you want to do something a little more complex, so the DOMDocumentFactory class constructor can take an instance DOMDocumentFactoryConfig class as its sole argument.

To create an instance of DOMDocumentFactoryConfig:

```
$DOMDocumentFactoryConfig = new DOMDocumentFactoryConfig(array $settings = [], \HTMLPurifier $inputPurifier = null, \HTMLPurifier $outputPurifier = null);
```

If you do not pass an instance of [HTMLPurifier](http://htmlpurifier.org) as `$inputPurifier` your settings for the HTMLPurifier will be used instead of a default HTMLPurifier object. By default no output purification is preformed. Should you want to purify the output an additional HTMLPurifier may be passed as `$outputPurifier`.

The configuration can also be modified after creating it:

```
$DOMDocumentFactoryConfig->setInputPurifier(\HTMLPurifier $purifier);
$DOMDocumentFactoryConfig->setOutputPurifier(\HTMLPurifier $purifier);
$DOMDocumentFactoryConfig->version = '1.0';
```

The `$settings` array defaults to:

```
$settings = [
    'version'             => '1.0',
    'encoding'            => 'UTF-8',
    'recover'             => true,
    'preserveWhiteSpace'  => false,
    'formatOutput'        => true,
    'DOMOptions'          => LIBXML_NOERROR | LIBXML_NOWARNING,
];
```

### As a Static Function

[](#as-a-static-function)

You can also use this factory as a one off static function. You can provide an optional `$DOMDocumentFactoryConfig` when you do so. Internally the static methods spin up an instance of the DOMDocumentFactory class to do their work, so this method of use is mostly just a shortcut to actually integrating the factory into a project.

```
$node = DOMDocumentFactory::getDomNode(string $blob, DOMDocumentFactoryConfig $config = null);

$string = DOMDocumentFactory::stringifyNode(\DOMNode $node, DOMDocumentFactoryConfig $config = null);

$array = DOMDocumentFactory::stringifyNodeList(\DOMNodeList $nodes, DOMDocumentFactoryConfig $config = null);
```

Change log
----------

[](#change-log)

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

Testing
-------

[](#testing)

```
$ composer test
```

The current tests are fairly basic; tests that more effectively attack possible edge cases or unexpected / unpredictable behaviors would be helpful.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) and [CODE\_OF\_CONDUCT](CODE_OF_CONDUCT.md) for details.

Security
--------

[](#security)

If you discover any security related issues, please email  instead of using the issue tracker.

Credits
-------

[](#credits)

- [Dane Lindberg](https://github.com/dlindberg)
- [All Contributors](../../contributors)

The boiler plate for this project is based on [ The League of Extraordinary Packages'](http://thephpleague.com) [Skeleton](https://github.com/thephpleague/skeleton) package repository.

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

25

—

LowBetter than 37% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity6

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity56

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

Unknown

Total

1

Last Release

2614d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/145a7517b65de71107e43e44c0dc0d7c1e8734b913fa931aaf9986f12e8f2ba1?d=identicon)[dlindberg](/maintainers/dlindberg)

---

Top Contributors

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

---

Tags

domdocumentDlindbergdoc factory

###  Code Quality

TestsPHPUnit

Code StylePHP\_CodeSniffer

### Embed Badge

![Health badge](/badges/dlindberg-dom-document-factory/health.svg)

```
[![Health](https://phpackages.com/badges/dlindberg-dom-document-factory/health.svg)](https://phpackages.com/packages/dlindberg-dom-document-factory)
```

###  Alternatives

[civicrm/civicrm-core

Open source constituent relationship management for non-profits, NGOs and advocacy organizations.

728272.9k17](/packages/civicrm-civicrm-core)[caxy/php-htmldiff

A library for comparing two HTML files/snippets and highlighting the differences using simple HTML.

21520.9M15](/packages/caxy-php-htmldiff)[getdkan/dkan

DKAN Open Data Catalog

385135.4k2](/packages/getdkan-dkan)[verbb/formie

The most user-friendly forms plugin for Craft.

101372.9k40](/packages/verbb-formie)[stevebauman/hypertext

The best HTML to text transformer

171472.6k2](/packages/stevebauman-hypertext)[trsteel/ckeditor-bundle

Symfony bundle for easy integration of the CKEditor WYSIWYG

99630.9k9](/packages/trsteel-ckeditor-bundle)

PHPackages © 2026

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