byjg / xmlutil
一个用于在PHP中轻松处理XML的实用工具类。
4.9.1
2024-01-03 23:22 UTC
Requires
- php: >=7.4
- ext-xml: *
Requires (Dev)
- phpunit/phpunit: ^9.5
README
一个用于在PHP中轻松处理XML的实用工具类
创建一个新的XML文档并添加节点
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');
将生成以下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);
基于XPath选择单个节点
$node = XmlUtil::selectSingleNode($xml, '//subnode');
基于XPath选择所有节点
$nodeList = XmlUtil::selectNodes($myNode, '//subnode');
处理xml命名空间
将命名空间添加到文档中
XmlUtil::addNamespaceToDocument($xml, 'my', 'http://www.example.com/mytest/');
将生成
<?xml version="1.0" encoding="utf-8"?> <root xmlns:my="http://www.example.com/mytest/"> ... </root>
使用命名空间前缀添加节点
XmlUtil::createChild($xml->documentElement, 'my:othernodens', 'teste');
使用命名空间添加节点
XmlUtil::createChild($xml->documentElement, 'nodens', 'teste', 'http://www.example.com/mytest/');
附加 - CleanDocument
XmlUtil有一个类,可以选择性地从文档中删除特定的标记(标签)或删除所有标记。
示例
<?php $document = new \ByJG\Util\CleanDocument($documentXmlOrHtml); $document ->removeContentByTag('a', 'name') ->removeContentByProperty('src') ->stripTagsExcept(['img']) ->get();
安装
composer require "byjg/xmlutil"
运行测试
vendor/bin/phpunit