How to objetify a DomDocument with hierarchy like:
<root>
<item>
<prop1>info1</prop1>
<prop2>info2</prop2>
<prop3>info3</prop3>
</item>
<item>
<prop1>info1</prop1>
<prop2>info2</prop2>
<prop3>info3</prop3>
</item>
</root>
It's possible to use in object style to retrieve information, as:
<?php
$theNodeValue = $aitem->prop1;
?>
Here is the code: one Class and 2 functions.
<?php
class ArrayNode{
public $nodeName, $nodeValue;
}
function getChildNodeElements( $domNode ){
$nodes = array();
for( $i=0; $i < $domNode->childNodes->length; $i++){
$cn = $domNode->childNodes->item($i);
if( $cn->nodeType == 1){
$nodes[] = $cn;
}
}
return $nodes;
}
function getArrayNodes( $domDoc ){
$res = array();
for( $i=0; $i < $domDoc->childNodes->length; $i++){
$cn = $domDoc->childNodes->item($i);
if( $cn->nodeType == 1){
$sub_cn = getChildNodeElements( $cn);
$baseItemTagName = $sub_cn[0]->nodeName;
break;
}
}
$dnl = $domDoc->getElementsByTagName( $baseItemTagName);
for( $i=0; $i< $dnl->length; $i++){
$arrayNode = new ArrayNode();
$arrayNode->nodeName = $dnl->item($i)->nodeName;
$arrayNode->nodeValue = $dnl->item($i)->nodeValue;
$cn = $dnl->item($i)->childNodes;
for( $k=0; $k<$cn->length; $k++){
if( $cn->item($k)->nodeName == "#text" && trim($cn->item($k)->nodeValue) == "") continue;
$arrayNode->{$cn->item($k)->nodeName} = $cn->item($k)->nodeValue;
}
$attr = $dnl->item($i)->attributes;
for( $k=0; $k < $attr->length; $k++){
if(! is_null($attr)){
if( $attr->item($k)->nodeName == "#text" && trim($attr->item($k)->nodeValue) == "") continue;
$arrayNode->{$attr->item($k)->nodeName} = $attr->item($k)->nodeValue;
}
}
$res[] = $arrayNode;
}
return $res;
}
?>
To use it:
<?php
$url = "/path/to/yourxmlfile.xml";
$domSrc = file_get_contents($url);
$dom = new DomDocument();
$dom->loadXML( $domSrc );
$ans = getArrayNodes( $dom );
for( $i=0; $i < count( $ans ) ; $i++){
$cn = $ans[ $i];
$info1 = $cn->prop1;
$info2 = $cn->prop2;
$info3 = $cn->prop3;
}
?>