Friday, January 22, 2010

Nested queries with DOM and Xpath

<?php
//CREATE NEW DOM INSTANCE
$doc = new DOMDocument();

//LOAD XML FROM FILE
$doc->load('data.xml');

//CREATE A NEW XPATH INSTANCE
$xpath = new DOMXpath($doc);

//ASSIGN FIRST XPATH TO VARIABLE
$containers = $xpath->query('/item/container');

//COUNT THE NUMBER OF NODELISTS
$count = $containers->length;

//LOOP THROUGH THE NODELISTS
for($i=0;$i<$count;$i++)
{
   //CREATE ANOTHER XPATH INSTANCE BASED ON THE PREVIOUS
   $subitems = $xpath->query('.//subitem',$containers->item($i));

   //COUNT THE NUMBER OF SUB-NODELISTS
   $subcount = $subitems->length;

   //LOOP THROUGH AND ACCESS ITEMS PER USUAL
   for($j=0;$j<$subcount;$j++)
   {
      //echo $containers->item($i)->...;
      //echo $subitems->item($j)->...;
   }
}
?>