Gle*_*rry 22 php casting simplexml
我需要以递归方式将PHP SimpleXMLObject强制转换为数组.问题是每个子元素也是PHP SimpleXMLElement.
这可能吗?
Aja*_*uel 64
json_decode(json_encode((array) simplexml_load_string($obj)), 1);
Run Code Online (Sandbox Code Playgroud)
没有测试这个,但这似乎完成了它:
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;
}
Run Code Online (Sandbox Code Playgroud)
取自http://www.codingforums.com/showthread.php?t=87283