1

I am currently learning different ways to iterate through the xml document tags using the php DOMDocument object, I understand the foreach loop for iterating through the tags, but the $element->item(0)->childNodes->item(0)->nodeValue is a bit unclear to me could somebody explain to me in detail? Thank you.

<?php
    $xmlDoc = new DOMDocument();
    $xmlDoc->load('StudentData.xml');

    $studentRoot = $xmlDoc->getElementsByTagName('Student');
    for ($i = 0; $i < ($studentRoot->length); $i++) {
        $firstNameTags = $studentRoot->item($i)->getElementsByTagName('FirstName');
        echo $firstNameTags->item(0)->childNodes->item(0)->nodeValue.' <br />';
    }

    /* so much easier and clear to understand! */
    foreach($studentRoot as $node) {

        /* For every <student> Tag as a separate node, 
           step into it's child node, and for each child,
           echo the text content inside */  

        foreach($node->childNodes as $child) {
            echo $child->textContent.'<br />';
        }
    }
?>
Sasidhar Vanga
  • 3,384
  • 2
  • 26
  • 47
Errol Wallace
  • 167
  • 2
  • 13

1 Answers1

3
$elements->item(0)->childNodes->item(0)->nodeValue

First:

$elements

The current elements$ as parsed and referenced. In the code example, that would be:

$firstNameTags = $studentRoot->item($i)->getElementsByTagName('FirstName');
$firstNameTags->...

Next:

->item(0)

Get a reference to the first of the $elements item in the node list. Since this is zero-indexed, ->item(0) would get the first node in the list by index.

->childNodes

Get a list of the child nodes to that first $elements node referenced by ->item(0) above. As there is no (), this is a (read only) property of the DOMNodeList.

->item(0)

Again, get the first node in the list of child nodes by index.

->nodeValue

The value of the node itself.


If the form of the state alone:

$obj->method()->method()->prop

Confuses you, look into method chaining, which is what this uses to put all of those method calls together.


$ Note, you left off the s, but that indicates there's one or more possible by convention. So $element would be zero or one element reference, $elements might be zero, one or more in a collection of $element.

Community
  • 1
  • 1
Jared Farrish
  • 48,585
  • 17
  • 95
  • 104