我需要以递归方式将PHP SimpleXMLObject强制转换为数组。问题是每个子元素也是一个PHP SimpleXMLElement。
这可能吗?
答案 0 :(得分:62)
json_decode(json_encode((array) simplexml_load_string($obj)), 1);
答案 1 :(得分:6)
没有测试过这个,但这似乎完成了它:
function convertXmlObjToArr($obj, &$arr)
{
$children = $obj->children();
foreach ($children as $elementName => $node)
{
$nextIdx = count($arr);
$arr[$nextIdx] = array();
$arr[$nextIdx]['@name'] = strtolower((string)$elementName);
$arr[$nextIdx]['@attributes'] = array();
$attributes = $node->attributes();
foreach ($attributes as $attributeName => $attributeValue)
{
$attribName = strtolower(trim((string)$attributeName));
$attribVal = trim((string)$attributeValue);
$arr[$nextIdx]['@attributes'][$attribName] = $attribVal;
}
$text = (string)$node;
$text = trim($text);
if (strlen($text) > 0)
{
$arr[$nextIdx]['@text'] = $text;
}
$arr[$nextIdx]['@children'] = array();
convertXmlObjToArr($node, $arr[$nextIdx]['@children']);
}
return;
}
答案 2 :(得分:0)
有可能。这是一个递归函数,它打印出父元素的标签和标签+不再有子元素的元素的内容。您可以更改它以构建数组:
foreach( $simpleXmlObject as $element )
{
recurse( $element );
}
function recurse( $parent )
{
echo '<' . $parent->getName() . '>' . "\n";
foreach( $parent->children() as $child )
{
if( count( $child->children() ) > 0 )
{
recurse( $child );
}
else
{
echo'<' . $child->getName() . '>';
echo iconv( 'UTF-8', 'ISO-8859-1', $child );
echo '</' . $child->getName() . '>' . "\n";
}
}
echo'</' . $parent->getName() . '>' . "\n";
}
答案 3 :(得分:0)
我没有看到这一点,因为SimpleXMLObject可以像数组一样被威胁......
但如果您确实需要,请在论坛中查看chassagnette在this thread或this post中的回答。
答案 4 :(得分:0)
取决于CDATA,数组等的一些麻烦。 (请参阅:SimpleXMLElement to PHP Array)
我认为,这将是最好的解决方案:
public function simpleXml2ArrayWithCDATASupport($xml)
{
$array = (array)$xml;
if (count($array) === 0) {
return (string)$xml;
}
foreach ($array as $key => $value) {
if (is_object($value) && strpos(get_class($value), 'SimpleXML') > -1) {
$array[$key] = $this->simpleXml2ArrayWithCDATASupport($value);
} else if (is_array($value)) {
$array[$key] = $this->simpleXml2ArrayWithCDATASupport($value);
} else {
continue;
}
}
return $array;
}
答案 5 :(得分:0)
在这里,我的迭代式(即使我认为您不会通过使用递归解析数据来解析堆栈)也会实现递归强制转换为数组。与通过json _ ** decode函数传递相比,这是一种更直接的方式:
function xml2Array(SimpleXMLElement $el): stdClass {
$ret = $el;
$stack = [&$ret];
while (count($stack) > 0) {
$cur = &$stack[count($stack) - 1];
array_splice($stack, -1);
$cur = (object) (array) $cur;
foreach ($cur as $key => $child) {
$childRef = &$cur->{$key};
if ($child instanceof SimpleXMLElement)
$stack[count($stack) - 1] = &$childRef;
elseif(is_array($child))
foreach ($childRef as $ckey => $cell) {
if ($cell instanceof SimpleXMLElement)
$stack[count($stack) - 1] = &$childRef[$ckey];
}
}
}
return $ret;
}
答案 6 :(得分:0)
对于那些对 CDATA 案件有疑虑的人,
将@ajayi-oluwaseun-emmanuel 的回答与 this answer 结合起来对我有用:
$xml = simplexml_load_string($xml_str, 'SimpleXMLElement', LIBXML_NOCDATA);
$json = json_encode($xml);
$arr = json_decode($json,TRUE);