Page 1 of 1
DOMDocument Accessing Child Elements
Posted: Tue Aug 07, 2007 8:45 am
by dethron
Code: Select all
$dom = new DOMDocument;
$dom->Load("books.xml";
$items = $dom->getElementsByTagName('BOOKS');
foreach ($items as $item) {
echo $item->nodeValue . "<br>";
}
this will print all the BOOKS inside books.xml. I need to access a single element. For example:
Code: Select all
echo $item->nodeValue->selectSubNode("AUTHOR");
I know there is no selectSubNode, this is what i need.
P.S : If I use
Code: Select all
$items = $dom->getElementsByTagName('AUTHOR');
then i will need another variable for ISDN numbers, i.e
Code: Select all
$items2 = $dom->getElementsByTagName('ISDN ');
This solution is bad since we cant know which sub elements exist

Re: DOMDocument Accessing Child Elements
Posted: Tue Aug 07, 2007 9:23 am
by volka
dethron wrote:This solution is bad since we cant know which sub elements exist

Then what is your application supposed to do?
Posted: Tue Aug 07, 2007 9:25 am
by dethron
volka i dont want to dumb the related data into different arrays, but wait

i am close to solution, soon i will post it here

Posted: Tue Aug 07, 2007 11:25 am
by dethron
feyd | Please use Code: Select all
and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]
Code: Select all
function dom2array($node){
$res = array();
//print $node->nodeType.'<br/>';
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;
}
I found this function very useful. When you have DOMDocument, you can convert the DOMObject to an array using this function. An example of usage is below:
Code: Select all
$dom = new DOMDocument;
$dom->Load($file);
$items = $dom->getElementsByTagName('TAGNAME');
for ($i = 0; $i < $items->length; $i++) {
$policeler[$i] = dom2array($items->item($i));
}
//print_r($policeler);
// the following line will give you the value of desired TAG,
// 0 (zero) implies the first element in the document.
echo $policeler[0]["TAGNAME"]["#text"];
feyd | Please use Code: Select all
and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]
Posted: Tue Aug 07, 2007 11:42 am
by volka
Why not using SimpleXML then?
http://de2.php.net/simplexml