Loop through each top level node to display its name in PHP

Description

The following code shows how to loop through each top level node to display its name.

Example


/*w  w w .  jav a  2  s .  co m*/
<?php
$xml = simplexml_load_file('test.xml');
// Get the element nodes at the top level of the XML document
$children = $xml->children();
echo $children . "<br/>";

// Loop through each top level node to display its name
foreach ($children as $child) {
  echo 'Node name: ' . $child->getName() . '<br />';
  // Get the attributes for the current node
  $attributes = $child->attributes();
  // Loop through the attributes of the current node
  foreach ($attributes as $attribute) {
    echo 'Attribute ' . $attribute->getName() . ": $attribute<br />";
  }
  // If the current node has no children, display its value
  if (false === $nextChildren = $child->children()) {
    echo "$child<br />";
  } else {
    // Otherwise loop through the next level
    foreach ($nextChildren as $nextChild) {
      echo $nextChild->getName() . ": $nextChild<br />";
    }
    echo '<br />';
  }
}
?>

The following code is for test.xml.


//from w ww. ja  v a2s .  com
<?xml version='1.0' encoding='utf-8'?>
<inventory>
  <book isbn13='1'>
    <title>PHP</title>
  <author>Jack</author>
  <publisher>Publisher 1</publisher>
  <description>PHP Book</description>
  </book>
  <book isbn13='2'>
    <title>XML</title>
  <author>Jane</author>
  <publisher>Publisher 2</publisher>
  <description>XML Book</description>
  </book>
</inventory>

The code above generates the following result.





















Home »
  PHP Tutorial »
    XML »




DOM
SimpleXML
SimpleXMLElement
XML Parser