Reading

To read an XML document, load it into a DOMDocument with load(), then navigate it with methods such as getElementsByTagName().

If the document contains XInclude directives, call $doc->xinclude() after loading to resolve them and merge in the included content. The example below loads people.xml, which pulls in the two <person> elements of people2.xml via <xi:include>, then iterates over all four <person> elements, printing each child element's text and the id attribute.

ch08-people.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!-- people.xml -->
<people xmlns:xi="http://www.w3.org/2003/XInclude">
   <xi:include href="people2.xml" parse="xml">
      <xi:fallback>
      <error>xinclude: people2.xml not found</error>
      </xi:fallback>
   </xi:include>

   <person id="p3">
      <name>Eric Lee</name>
      <gender>m</gender>
      <age>35</age>
   </person>
   <person id="p4">
      <name>Serena</name>
      <gender>f</gender>
      <age>25</age>
   </person>
</people>

ch08-people2.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!-- people2.xml -->
<people>
   <person id="p1">
      <name>Alexander Mike</name>
      <gender>m</gender>
      <age>40</age>
   </person>
   <person id="p2">
      <name>Celeste</name>
      <gender>f</gender>
      <age>15</age>
   </person>
</people>

<!DOCTYPE html>
<html><head></head><body><?php

$doc = new DOMDocument();
$doc->load('people.xml');
$doc->xinclude();
$persons = $doc->getElementsByTagName('person');
foreach ($persons as $person){
   $v = $person->getElementsByTagName('*');
   for ($i=0; $i<$v->length; $i++){
      echo $v->item($i)->nodeValue.",";
   }
   echo $person->attributes->getNamedItem('id')->value;
   echo "<br/>";
}

?></body></html>

Alexander Mike,m,40,p1 Celeste,f,15,p2 Eric Lee,m,35,p3 Serena,f,25,p4