A utility class to make easy work with XML in PHP.
MIT License
A utility class to make easy work with XML in PHP
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"?>
<root>
<mynode>
<subnode>text</subnode>
<subnode>more text</subnode>
<othersubnode attr="value">other text</othersubnode>
</mynode>
</root>
$array = XmlUtil::xml2Array($xml);
$node = XmlUtil::selectSingleNode($xml, '//subnode');
$nodeList = XmlUtil::selectNodes($myNode, '//subnode');
Add a namespace to the document
XmlUtil::addNamespaceToDocument($xml, 'my', 'http://www.example.com/mytest/');
will produce
<?xml version="1.0" encoding="utf-8"?>
<root xmlns:my="http://www.example.com/mytest/">
...
</root>
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', 'http://www.example.com/mytest/');
XmlUtil have a class for selectively remove specific marks (tags) from the document or remove all marks.
Example:
<?php
$document = new \ByJG\Util\CleanDocument($documentXmlOrHtml);
$document
->removeContentByTag('a', 'name')
->removeContentByProperty('src')
->stripTagsExcept(['img'])
->get();
composer require "byjg/xmlutil"
vendor/bin/phpunit
flowchart TD
byjg/xmlutil --> ext-xml