I want to parse xml files, The best way I found is to use DOMDocument() class so far.
sample xml string:
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<response>
<resData>
<contact:infData xmlns:contact="http://example.com/contact-1.0">
<contact:status s="value1"/>
<contact:status s="value2"/>
<contact:status s="value3"/>
<contact:status s="value4"/>
</contact:infData>
</resData>
</response>
I use function dom2array (bellow) to parse dom, but it only return 1 element (value4 only)
<?php
function dom2array($node) {
$res = array();
if($node->nodeType == XML_TEXT_NODE){
$res = $node->nodeValue;
}else{
if($node->hasAttributes()){
$attributes = $node->attributes;
if(!is_null($attributes)){
$res['@attributes'] = array();
foreach ($attributes as $index=>$attr) {
$res['@attributes'][$attr->name] = $attr->value;
}
}
}
if($node->hasChildNodes()){
$children = $node->childNodes;
for($i=0;$i<$children->length;$i++){
$child = $children->item($i);
$res[$child->nodeName] = dom2array($child);
}
}
}
return $res;
}
?>
Is there any way to parse all xml elements and sent them to an array?
output array:
Array
(
[response] => Array
(
[#text] =>
[resData] => Array
(
[#text] =>
[contact:infData] => Array
(
[#text] =>
[contact:status] => Array
(
[@attributes] => Array
(
[s] => value4
)
)
)
)
)
)
Where is value1, value2, value3 ? :( Thank you
See Question&Answers more detail:os