Payne's PHP Notes

Back to Payne's PHP Notebook.

10. XML Parsers (Expat, DOM, SimpleXML)

Expat XML Parser:

Syntax / Example Result
/* HarryPotter.xml */
<?xml version="1.0" encoding="utf-8" ?>
<book>
  <title>Harry Potter and the Sorserer's Stone</title>
  <author>J. K. Rowling</author>
</book>
 
<?php

$parser = xml_parser_create();

// Handler for the start of an element.
function processStart($parser, $elementName, $elementAttribute)
{
  switch($elementName)
  {
    // CAPITAL required!
    case "BOOK":
      echo "=== Start of Book ===<br />";
      break;
    case "TITLE":
      echo "Title: ";
      break;
    case "AUTHOR":
      echo "Author: ";
      break;
  }
}

// Handler for the end of an element
function processEnd($parser, $elementName)
{
  switch($elementName)
  {
    case "BOOK":
      echo "=== End of Book ===";
  }

  echo "<br /><br />";
}

// Handler for char data
function processChar($parser, $charData)
{
  echo $charData;
}

// Set element handler (start and end)
xml_set_element_handler($parser, "processStart", "processEnd");

// Set character data handler
xml_set_character_data_handler($parser, "processChar");

// Open XML file for read
$xmlFile = fopen("HarryPotter.xml", "r");

// Read XML file
if($data=fread($xmlFile, filesize("HarryPotter.xml")))
{
  xml_parse($parser, $data) or
    die(sprintf("XML error: %s", xml_error_string(xml_get_error_code($parser))));
}

// Free the parser
xml_parser_free($parser);

?>
=== Start of Book ===

Title: Harry Potter and the Sorserer's Stone

Author: J. K. Rowling

=== End of Book ===

DOM:

Syntax / Example Result
<?php

// Create a DOMDocument object.
$domDoc = new DOMDocument();

// Load file.
$domDoc->load("HarryPotter.xml");

// Retrieve the element from DOMDocument object.
$element = $domDoc->documentElement;

// Loop through each child nodes and print information.
foreach($element->childNodes as $item)
{
  print $item->nodeName . " = " . $item->nodeValue . "<br />";
}

?>
#text =
title = Harry Potter and the Sorserer's Stone
#text =
author = J. K. Rowling
#text =

SimpleXML:

Syntax / Example Result
<?php

// Load XML file.
$xml = simplexml_load_file("HarryPotter.xml");

// Echo the name of the first element.
echo $xml->getName() . "<br />";

// Loop through each child of current element.
foreach($xml->children() as $child)
{
  // Display information.
  echo $child->getName() . " = " . $child . "<br />";
}

?>
book
title = Harry Potter and the Sorserer's Stone
author = J. K. Rowling