jwallace.us

tech, tunes, and other stuff

SimpleXML

The SimpleXML library in PHP converts XML into objects that can be accessed like an array.   There is both an object oriented and a procedural way of doing it:

Loading an XML file:

1
2
$xml_object = simplexml_load_file ('file_name.xml');
$xml_object = new SimpleXMLElement ('file_name.xml', NULL, true);

Loading an XML string:

1
2
3
$xml_string = file_get_contents ('file_name.xml');
$xml_object = simplexml_load_string ($xml_string);
$xml_object = new SimpleXMLElement ($xml_string);

With both the procedural and object oriented approaches a SimpleXMLElement object is returned.  What SimpleXMLElement provides is a way to access the XML document as you would an array.  For example,  given the following XML document:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?xml version="1.0"?>
<ncaa>
   <conference name="SEC">
   <team>
      <name>Florida</name>
      <division>East</division>
   </team>
   <team>
      <name>Georgia</name>
      <division>East</division>
   </team>
   <team>
      <name>Kentucky</name>
      <division>East</division>
   </team>
   <team>
      <name>South Carolina</name>
      <division>East</division>
   </team>
   <team>
      <name>Tennessee</name>
      <division>East</division>
   </team>
   <team>
      <name>Vanderbilt</name>
      <division>East</division>
   </team>
   </conference>
</ncaa>

…and this code:

1
2
3
4
5
6
7
8
9
10
<?php
   $xml_string = file_get_contents ('sec_football.xml');
   $xml_object = simplexml_load_string ($xml_string);
   foreach ($xml_object->conference as $conf) {
      echo $conf['name'] . "\n\n";
      foreach ($conf as $team) {
         echo "$team->name\n$team->division\n\n";
      }
}
?>

…produces the following output:

SEC
Florida
East
Georgia
East
Kentucky
East
South Carolina
East
Tennessee
East
Vanderbilt
East

Below is another way of producing the same output.  Note the use of the children() and attributes() functions.  Unlike the previous example, specific knowledge of the tag and attribute names was not needed:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?php
   $xml_object = new SimpleXMLElement ('sec_football.xml', NULL, true);
   list_all ($xml_object);

   function list_all($xml_object) {
      if ($xml_object != NULL) {
         $attr = $xml_object->attributes();
         if ($attr[0] != NULL) {
            echo $attr[0] . "\n\n";
         }
         echo trim($xml_object);
         foreach ($xml_object->children() as $child) {
            # to get the tag name itself you would
            # use the $child->getName() function
            list_all($child);
         }
         echo "\n";
      }
   }
?>