[RESOLVED] SimpleXML or DOM XML

liunx

Guest
Since both are available in PHP5, which is better?

Well, let me narrow that down. Which would be better for someone who wants to read an XML Document and then get information from it with specific tags (easy enough with simplexml) and then for each tag that has children, itterate through them grabbing their information. Would parse_xml work in this case too?

So an XML file like:

<?xml version="1.0" enctype="ISO-8859-1"?>
<parent>
<docTitle>My Page</docTitle>
<docAuthor>Me, of course!!</docAuthor>
<docWebsite>Where you are!!</docWebsite>

<section>
<sectTitle>Section 1</secTitle>
<secHead>A general toic overview of it</secHead>
<descrip>A more in-depth description of it</descrip>
</section>

<section>
<sectTitle>Section 1</secTitle>
<secHead>A general toic overview of it</secHead>
<descrip>A more in-depth description of it</descrip>
</section>
</parent>

So with SimpleXML, i can get the item names easily enough:
$xml = simplexml_load_file('file.xml');
$xml->docTitle;
$xml->docAuth;
$xml->docWebsite;

// Here's where I'm stuck
// I can get each item like so:
$xml->section[0]->sectTitle;

Except that I want to be able to set up a loop that for each <section>, I can extract what's inside of it (obviously since it's XML, it has to be fairly uniform as to what I can expect) and use it later.

Thanks for any help. And if you suggest I use DOMDocument, can you point me in the direction of where I need to be? I spent a few hours perusing the PHP Manual last night, and trying a few different things. I have access to PHP 4 & 5 so really any solution would work.SimpleXMLElement has an iterator interface.

foreach ($xml->section as $section) {
echo $section->secTitle;
}

With DOMDocument, you would probably use DOMDocument::getElementsByTagName() which returns a DOMNodeList that you can iterate through.

Or you also do an XPath query if you like working with XPath (and you can do XPath with either SimpleXML or DOM), though XPath seems a bit overkill for this task.Why, why is it that last night when I tried that, it didn't work. And now it does....

Thanks dream.... much appreciated.
 
Back
Top