Skip to main content


Build Status Opensource ByJG GitHub source GitHub license GitHub release

A utility class to make easy work with XML in PHP

Create a new XML Document and add nodes

use ByJG\Util\XmlUtil;

$xml = XmlUtil::createXmlDocumentFromStr('<root />');

$myNode = XmlUtil::createChild($xml->documentElement, 'mynode');
XmlUtil::createChild($myNode, 'subnode', 'text');
XmlUtil::createChild($myNode, 'subnode', 'more text');
$otherNode = XmlUtil::createChild($myNode, 'othersubnode', 'other text');
XmlUtil::addAttribute($otherNode, 'attr', 'value');

will produce the follow xml

<?xml version="1.0" encoding="utf-8"?>
<subnode>more text</subnode>
<othersubnode attr="value">other text</othersubnode>

Convert to array

$array = XmlUtil::xml2Array($xml);

Select a single node based on XPath

$node = XmlUtil::selectSingleNode($xml, '//subnode');

Select all nodes based on XPath

$nodeList = XmlUtil::selectNodes($myNode, '//subnode');

Working with xml namespaces

Add a namespace to the document

XmlUtil::addNamespaceToDocument($xml, 'my', '');

will produce

<?xml version="1.0" encoding="utf-8"?>
<root xmlns:my="">

Add a node with a namespace prefix

XmlUtil::createChild($xml->documentElement, 'my:othernodens', 'teste');

Add a node with a namespace

XmlUtil::createChild($xml->documentElement, 'nodens', 'teste', '');

Bonus - CleanDocument

XmlUtil have a class for selectively remove specific marks (tags) from the document or remove all marks.



$document = new \ByJG\Util\CleanDocument($documentXmlOrHtml);

->removeContentByTag('a', 'name')


composer require "byjg/xmlutil"

Running the Tests



Open source ByJG