#native_company# #native_desc#

Converting XML into a PHP data structure Page 2

By PHP Builder Staff
on December 25, 2002

A Look At The XML File Structure

XML files are designed to be validated against a DTD and store data in a
format similar to something you’d see in an HTML document. All tags are
just made up on the fly (as defined by a DTD) and can represent a tree
structure. Here is an example of some XML:
    <?xml version="1.0" encoding="UTF-8"?>
    <!-- This is just a comment, ignore it -->
    <drive desc="Letters and Numbers Harddrive">
        <folder name="folder01">
            <file name="a.txt"/>
            <file name="b.txt"></file>
        <folder name="folder02">
            <file name="c.txt"/>
            <file name="d.txt" owner="bob">
            This is a comment about file d.
            We like comments.</file>
Now, if you look at this document, you’ll notice that there exists one
<drive> tag with two folder tags inside it. Also,
each folder tag contains two file tags within
them. This file creates a tree-like structure of data. Now, we would
like to access this data from within PHP. There are many ways to get
to this data from within PHP including:
  • manually parsing the XML file,
  • parsing the file with the PHP SAX parser,
  • using the XPath libraries to search and pull data,
  • or using the DOM parser
The manual option is not our most robust solution, and the DOM support in
PHP is still experimental. So, I’ve chosen to use the SAX parser route.
However, unlike similar other solutions, I’d like to write an object in
PHP that parses this XML document into a PHP data structure so that I can
access the data like any other PHP data instead of having to write a custom
parser each time I use XML in an application.