PHPackages                             s9e/sweetdom - 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. [Templating &amp; Views](/categories/templating)
4. /
5. s9e/sweetdom

ActiveLibrary[Templating &amp; Views](/categories/templating)

s9e/sweetdom
============

Syntactic sugar for the DOM API with a focus on XSLT 1.0 template manipulation.

3.4.1(2y ago)32.0M—6.2%11MITPHPPHP ^8.1

Since May 24Pushed 2y ago3 watchersCompare

[ Source](https://github.com/s9e/SweetDOM)[ Packagist](https://packagist.org/packages/s9e/sweetdom)[ Docs](https://github.com/s9e/SweetDOM/)[ RSS](/packages/s9e-sweetdom/feed)WikiDiscussions master Synced 1mo ago

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

Overview
--------

[](#overview)

s9e\\SweetDOM is a library that extends [PHP's DOM extension](https://www.php.net/manual/en/book.dom.php) to make DOM manipulation easier, with a particular emphasis on XSLT 1.0 templates. It adds syntactic sugar for the most common DOM operations, [improves compatibility](#backward-and-forward-compatibility-with-older-and-future-versions-of-php) across PHP versions, and implements polyfills for some of the newer methods.

[![Code Coverage](https://camo.githubusercontent.com/7a2402528989b3166bec458b55bb1e1f4e61d1c2508ef754fa5f7fdd419ece36/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f7339652f5377656574444f4d2f6261646765732f636f7665726167652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/s9e/SweetDOM/?branch=master)[![Scrutinizer Code Quality](https://camo.githubusercontent.com/bae145c97207af2c74bc552b5ef67337bea5a057eabd201fa6385d62dc71a744/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f7339652f5377656574444f4d2f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/s9e/SweetDOM/?branch=master)

Installation
------------

[](#installation)

```
composer require s9e/sweetdom
```

API
---

[](#api)

#### s9e\\SweetDOM\\Document

[](#s9esweetdomdocument)

The `s9e\SweetDOM\Document` class extends `DOMDocument` and provides quick access to DOMXPath's `evaluate` and `query` methods. The `firstOf` method evaluates the XPath query and returns the first node of the list, or `null` if the list is empty.

```
mixed       evaluate(string $expression, ?DOMNode $contextNode = null, bool $registerNodeNS = true)
?DOMNode    firstOf(string $expression, ?DOMNode $contextNode = null, bool $registerNodeNS = true)
DOMNodeList query(string $expression, ?DOMNode $contextNode = null, bool $registerNodeNS = true)
```

The `s9e\SweetDOM\Document` class has a `$nodeCreator` property that provides a set of methods to create elements with an emphasis on XSL elements commonly used in templates. See `s9e\SweetDOM\NodeCreator` for the full content.

```
Comment createComment(string $data)
Element createElement(string $nodeName, string $textContent = '')
Element createElementNS(?string $namespace, string $nodeName, string $textContent = '')
Element createXslApplyTemplates(string $select = null, string $mode = null)
Element createXslAttribute(string $name, string $textContent = '', string $namespace = null)
Element createXslChoose()
Element createXslComment(string $textContent = '')
Element createXslCopyOf(string $select)
Element createXslElement(string $name, string $namespace = null, string $useAttributeSets = null)
Element createXslIf(string $test, string $textContent = '')
Element createXslOtherwise(string $textContent = '')
Element createXslText(string $textContent = '', string $disableOutputEscaping = null)
Element createXslValueOf(string $select, string $disableOutputEscaping = null)
Element createXslVariable(string $name, string $select = null)
Element createXslWhen(string $test, string $textContent = '')
```

#### s9e\\SweetDOM\\Element

[](#s9esweetdomelement)

The `s9e\SweetDOM\Element` class extends `DOMElement` and provides a set of magic methods to simultaneously create a node and insert it relative to the element. For each method from the `s9e\SweetDOM\NodeCreator` class, exist five corresponding methods on the `s9e\SweetDOM\Element`.

For instance, the `createXslText` method from `s9e\SweetDOM\NodeCreator` is declined into the `afterXslText`, `appendXslText`, `beforeXslText`, `prependXslText`, and `replaceWithXslText` methods in `s9e\SweetDOM\Element`. Each method creates a node, performs the DOM action, then returns the node. The following example illustrates where each `xsl:text` element is inserted relative to the `span` element from which they are created, then replaces the `br` element.

```
$xsl = '

';

$dom                     = new s9e\SweetDOM\Document;
$dom->formatOutput       = true;
$dom->preserveWhiteSpace = false;
$dom->loadXML($xsl);

$span    = $dom->firstOf('//span');
$methods = ['afterXslText', 'appendXslText', 'beforeXslText', 'prependXslText'];
foreach ($methods as $methodName)
{
	$span->$methodName($methodName);
}
$dom->firstOf('//br')->replaceWithXslText('replaceWithXslText');
echo $dom->saveXML($dom->documentElement);
```

```

    beforeXslText

      prependXslText
      replaceWithXslText
      appendXslText

    afterXslText

```

XPath methods are also accessible at the element level and use the element itself as context node:

```
$dom = new s9e\SweetDOM\Document;
$dom->loadXML('');

var_dump($dom->firstOf('//x')->getAttribute('id'));
var_dump($dom->firstOf('//x')->firstOf('x')->getAttribute('id'));
```

```
string(1) "1"
string(1) "2"

```

Elements can be easily created and added relative to the context node via the following API:

```
Element afterElement(string $nodeName, string $textContent = '')
Element appendElement(string $nodeName, string $textContent = '')
Element beforeElement(string $nodeName, string $textContent = '')
Element prependElement(string $nodeName, string $textContent = '')
```

```
$dom                     = new s9e\SweetDOM\Document;
$dom->formatOutput       = true;
$dom->preserveWhiteSpace = false;
$dom->loadXML('');

$span    = $dom->firstOf('//span');
$methods = ['afterElement', 'appendElement', 'beforeElement', 'prependElement'];
foreach ($methods as $methodName)
{
	$span->$methodName('i', $methodName);
}
echo $dom->saveXML($dom->documentElement);
```

```

  beforeElement

    prependElement

    appendElement

  afterElement

```

Document fragments can be used to batch operations, or insert XML in a DOM.

```
$dom = new s9e\SweetDOM\Document;
$dom->loadXML('');

$x = $dom->firstOf('//x');
$x->appendDocumentFragment(
	// The callback will be executed before the fragment is appended
	fn($fragment) => $fragment->appendXML('')
);

echo $dom->saveXML($x);
```

```

```

#### Other extended nodes

[](#other-extended-nodes)

The following DOM nodes are automatically extended and augmented with XPath methods as well as whichever magic methods are supported by the node type, usually via the [`DOMChildNode`](https://www.php.net/manual/class.domchildnode.php) and [`DOMParentNode`](https://www.php.net/manual/class.domparentnode.php) interfaces.

- `s9e\SweetDOM\Attr` extends `DOMAttr`
- `s9e\SweetDOM\CdataSection` extends `DOMCdataSection`
- `s9e\SweetDOM\Comment` extends `DOMComment`
- `s9e\SweetDOM\DocumentFragment` extends `DOMDocumentFragment`
- `s9e\SweetDOM\Element` extends `DOMElement`
- `s9e\SweetDOM\Text` extends `DOMText`

Backward and forward compatibility with older and future versions of PHP
------------------------------------------------------------------------

[](#backward-and-forward-compatibility-with-older-and-future-versions-of-php)

In order to improve compatibility with older versions of PHP as well as future versions of PHP, this library uses a different set of classes to implement node types depending on the PHP version. The base classes are those listed above, in the `s9e\SweetDOM` namespace, and only those classes should be used when checking for class types.

#### Backward compatibility with older versions of PHP

[](#backward-compatibility-with-older-versions-of-php)

Polyfills for the following methods are provided for PHP &lt; 8.3:

- `Node::isEqualNode`
- `ParentNode::insertAdjacentElement`
- `ParentNode::insertAdjacentText`
- `ParentNode::replaceChildren`

On PHP older than 8.1.23, and on PHP versions from 8.2.0 to 8.2.9, the following methods are emulated:

- `ChildNode::after`
- `ChildNode::before`
- `ChildNode::replaceWith`
- `ParentNode::append`
- `ParentNode::prepend`

#### Forward compatibility with future versions of PHP

[](#forward-compatibility-with-future-versions-of-php)

The following methods have been modified to match PHP 8.3's behaviour with regards to disconnected nodes (nodes with no parent) and align with the DOM specification.

- `ChildNode::after`
- `ChildNode::before`
- `ChildNode::replaceWith`

###  Health Score

42

—

FairBetter than 90% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity45

Moderate usage in the ecosystem

Community12

Small or concentrated contributor base

Maturity73

Established project with proven stability

 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 ~100 days

Recently: every ~29 days

Total

15

Last Release

786d ago

Major Versions

1.0.1 → 2.0.0-alpha.12020-12-08

2.1.2 → 3.0.02023-10-13

2.1.0.1 → 3.3.02023-12-21

PHP version history (4 changes)1.0.0PHP &gt;=7.1

2.1.1PHP &gt;=8.0

3.0.0PHP &gt;=8.1

3.3.0PHP ^8.1

### Community

Maintainers

![](https://www.gravatar.com/avatar/06ce60f935a636cbb13d7ca4733fa28c9a2c9d500834c6481f86e05fd4a55e86?d=identicon)[s9e](/maintainers/s9e)

---

Top Contributors

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

---

Tags

dom-manipulationdomxslxslt

###  Code Quality

TestsPHPUnit

Code StylePHP CS Fixer

### Embed Badge

![Health badge](/badges/s9e-sweetdom/health.svg)

```
[![Health](https://phpackages.com/badges/s9e-sweetdom/health.svg)](https://phpackages.com/packages/s9e-sweetdom)
```

###  Alternatives

[veewee/xml

XML without worries

1835.9M29](/packages/veewee-xml)[sinnbeck/laravel-dom-assertions

106250.5k8](/packages/sinnbeck-laravel-dom-assertions)[epic-64/elem

A fluent, type-safe PHP library for building HTML documents using the DOM

272.9k](/packages/epic-64-elem)

PHPackages © 2026

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