Use PHP to iterate through XML document tree

The Document Object Model (DOM) is an application programming interface (API) for valid HTML and well-formed XML documents. It defines the logical structure of documents and the way a document is accessed and manipulated. In the DOM specification, the term “document” is used in the broad sense – increasingly, XML is being used as a way of representing many different kinds of information that may be stored in diverse systems, and much of this would traditionally be seen as data rather than as documents. Nevertheless, XML presents this data as documents, and the DOM may be used to manage this data

To iterate through the xml tree we can use the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php
     function walk_tree ($node, $depth = 0) {
          for ($i = 0, $indent = ''; $i < $depth; $i++)
               $indent .= '     ';
          if ($node->type == XML_ELEMENT_NODE) {
                print ($indent . $node->tagname . "\n");
                $kids = $node->children ();
                $nkids = count ($kids);
                if ($nkids > 0) {
                     $depth++;
                     for ($i = 0; $i < $nkids; $i++)
                          walk_tree ($kids[$i], $depth);
                     $depth--;
               }
          }
     }
     $doc = xmldocfile ('contact.xml');
     print ("\n");
     walk_tree ($doc->root ());
     print ("\n");
?>

The input xml would be:

1
2
3
4
5
6
7
8
9
10
11
12
<contact id="43956">
     <personal>
          <name>
               <first>J</first>
               <middle>J</middle>
               <last>J</last>
          </name>
          <title>Manager</title>
          <employer>National</employer>
          <dob>1971-12-22</dob>
     </personal>
</contact>
Share Article/Example:
  • Facebook
  • Twitter
  • del.icio.us
  • Digg
  • DotNetKicks
  • DZone