Voting

: min(nine, two)?
(Example: nine)

The Note You're Voting On

sites.sitesbr.net
12 years ago
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);
# The first is the root tag...
if( $cn->nodeType == 1){
# But we want it's childNodes.
$sub_cn = getChildNodeElements( $cn);
# Found the tagName:
$baseItemTagName = $sub_cn[0]->nodeName;
break;
}
}

$dnl = $domDoc->getElementsByTagName( $baseItemTagName);

for(
$i=0; $i< $dnl->length; $i++){
$arrayNode = new ArrayNode();

# Summary
$arrayNode->nodeName = $dnl->item($i)->nodeName;
$arrayNode->nodeValue = $dnl->item($i)->nodeValue;

# Child Nodes
$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;
}

# Attributes
$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

# First you load a XML in a DomDocument variable.

$url = "/path/to/yourxmlfile.xml";
$domSrc = file_get_contents($url);
$dom = new DomDocument();
$dom->loadXML( $domSrc );

# Then, you get the ArrayNodes from the DomDocument.

$ans = getArrayNodes( $dom );


for(
$i=0; $i < count( $ans ) ; $i++){

$cn = $ans[ $i];

$info1 = $cn->prop1;
$info2 = $cn->prop2;
$info3 = $cn->prop3;

// ...

}

?>

<< Back to user notes page

To Top