tags:

views:

444

answers:

2

All,

I have an XML document that looks something like this:

<root>
    <profile>
     <childA>
     <childB>
     <childC>
    <profile>
    <blah>
    <blah>
    <foo>
    <bar>
<root>

I'd like to be able to grab the 'profile' node, then iterate through it's children ('childA', 'childB', etc)

So far, my code looks like this:

$doc = new DomDocument();
$doc->loadXML(file_get_contents("php://input"));
$profile_node = $doc->getElementsByTagName("profile")->item(0);

So far, so good. $profile_node has what I want.

In PHP4, I guess you'd do something like this:

$childnodes = $profile_node->child_nodes();
foreach ($childnodes as $node) {
    // do something with this node
}

But, I can't find the equivalent of child_nodes() in PHP5.

Since I'm pretty much a noob regarding PHP, I'd really appreciate a code example, so I can see the exact syntax.

Many thanks in advance!

Cheers, Matt

+1  A: 

According to the php manual, the DomNode class has a public $childNodes variable. You can access it directly:

foreach ($profile_node->childNodes as $node) {
    // do something with this node
}
Zed
Zed - Thanks for your response!My apologies - I should have mentioned that I don't know PHP well at all. So, I don't know the syntax for creating a loop that will iterate through the child nodes.Can you provide a code example (e.g., using a foreach loop)?No worries if not.
mattstuehler
You can just replace your foreach loop with the given foreach loop and delete the line directly above it.
Scharrels
Correct. This completely replaces your code below "In PHP4, I guess you'd do something like this"
Zed
Just a note - I screwed up my own code above. Instead of "$profile_node = $doc->getElementsByTagName("profile");", it should read: "$profile_node = $doc->getElementsByTagName("profile")->item(0);"
mattstuehler
+1  A: 

If you only need to read, I would suggest using the simplexml package:

$xml = simplexml_load_file('php://input');
$childnodes = $xml->xpath("//profile/child::*");
foreach($childnodes as $node){
  // do something
}

The SimpleXML package and the DOM package are interchangeable: you can import the SimpleXML into DOM objects using dom_import_simplexml().

Scharrels