PHP: XMLParser.php

Public Domain Dedication
This work is dedicated to the Public Domain.

This is a simple abstraction layer for PHP that allows XML input to be treated as a nested array.

UPDATED 12-Feb-2007: This version includes two bug fixes:

Sample usage:

  require_once('XMLParser.php');

... string buffer ...
  $data = '<?xml version="1.0" encoding="ISO-8859-1" ?>
<country name="usa">
    <city name="mountain view">baz
        <user>Jack</user>
        <user>Jill</user>bam
    </city>
</country>
';
  $parser = new XMLParser($data, 'raw', 1);
  $tree = $parser->getTree();

... file handle ...
  if($fh = popen("./demo.pl", "r")) {
    $parser = new XMLParser($fh, 'stream', 1);
    $result = $parser->getTree();
    pclose($fh);
  }

... file name ...
  $parser = new XMLParser('./foo.xml', 'file', 1);
  $tree = $parser->getTree();

... url ...
  $parser = new XMLParser('http://example.com/foo.xml', 'url', 1);
  $tree = $parser->getTree();

... view output ...
  // Display the array
  echo '<PRE>';
  print_r($tree);
  echo '</PRE>';
  

Download XMLParser.php

Note! You may need to increase memory and time limits to parse very large XML files. One developer who used the parser, Ashifi, pointed out:

Your XML parser is a saver! You might want to include a note about
increasing memory and script execution time. Insert the following
lines in XMLParser.php, before 'class XMLParser { ...'

ini_set("memory_limit", "1500M");
set_time_limit(500);

That's kind of extreme, but I had to read some XML files that were
several MB's large.