【发布时间】:2019-05-15 14:54:45
【问题描述】:
是否有不需要任何扩展或外部依赖的原生 PHP XML 解析器?
我可以使用simplexml_load_string() 进行解析,但如果服务器php 没有加载扩展,则此代码将失败。
【问题讨论】:
标签: php xml dependencies
是否有不需要任何扩展或外部依赖的原生 PHP XML 解析器?
我可以使用simplexml_load_string() 进行解析,但如果服务器php 没有加载扩展,则此代码将失败。
【问题讨论】:
标签: php xml dependencies
simplexml 默认启用,因此除非您使用的是非常旧的服务器,否则您应该很好。
在这种情况下,你可以使用这个:
<?php
function xmlObjToArr($obj) {
$namespace = $obj->getDocNamespaces(true);
$namespace[NULL] = NULL;
$children = array();
$attributes = array();
$name = strtolower((string)$obj->getName());
$text = trim((string)$obj);
if( strlen($text) <= 0 ) {
$text = NULL;
}
// get info for all namespaces
if(is_object($obj)) {
foreach( $namespace as $ns=>$nsUrl ) {
// atributes
$objAttributes = $obj->attributes($ns, true);
foreach( $objAttributes as $attributeName => $attributeValue ) {
$attribName = strtolower(trim((string)$attributeName));
$attribVal = trim((string)$attributeValue);
if (!empty($ns)) {
$attribName = $ns . ':' . $attribName;
}
$attributes[$attribName] = $attribVal;
}
// children
$objChildren = $obj->children($ns, true);
foreach( $objChildren as $childName=>$child ) {
$childName = strtolower((string)$childName);
if( !empty($ns) ) {
$childName = $ns.':'.$childName;
}
$children[$childName][] = xmlObjToArr($child);
}
}
}
return array(
'name'=>$name,
'text'=>$text,
'attributes'=>$attributes,
'children'=>$children
);
}
【讨论】:
domDocument 功能可以很好地处理 html 和 xml。没有外部依赖。
$xml = ''; //some xml string.
$dom = new domDocument;
$dom->loadHTML($xml);
【讨论】:
ext-dom 不在composer.json 中...所以我猜这是一个依赖项?