05.05.2013 Views

Programming PHP

Programming PHP

Programming PHP

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

complex than it seems. The easiest and quickest solution is to use the XML parser<br />

that ships with <strong>PHP</strong>.<br />

<strong>PHP</strong>’s XML parser is based on the Expat C library, which lets you parse but not validate<br />

XML documents. This means you can find out which XML tags are present and<br />

what they surround, but you can’t find out if they’re the right XML tags in the right<br />

structure for this type of document. In practice, this isn’t generally a big problem.<br />

<strong>PHP</strong>’s XML parser is event-based, meaning that as the parser reads the document, it<br />

calls various handler functions you provide as certain events occur, such as the<br />

beginning or end of an element.<br />

In the following sections we discuss the handlers you can provide, the functions to<br />

set the handlers, and the events that trigger the calls to those handlers. We also provide<br />

sample functions for creating a parser to generate a map of the XML document<br />

in memory, tied together in a sample application that pretty-prints XML.<br />

Element Handlers<br />

When the parser encounters the beginning or end of an element, it calls the start and<br />

end element handlers. You set the handlers through the xml_set_element_handler( )<br />

function:<br />

xml_set_element_handler(parser, start_element, end_element);<br />

The start_element and end_element parameters are the names of the handler<br />

functions.<br />

The start element handler is called when the XML parser encounters the beginning of<br />

an element:<br />

my_start_element_handler(parser, element, attributes);<br />

It is passed three parameters: a reference to the XML parser calling the handler, the<br />

name of the element that was opened, and an array containing any attributes the<br />

parser encountered for the element. The attribute array is passed by reference for<br />

speed.<br />

Example 11-2 contains the code for a start element handler. This handler simply<br />

prints the element name in bold and the attributes in gray.<br />

Example 11-2. Start element handler<br />

function start_element($inParser, $inName, &$inAttributes) {<br />

$attributes = array( );<br />

foreach($inAttributes as $key) {<br />

$value = $inAttributes[$key];<br />

$attributes[] = "$key=\"$value\" ";<br />

}<br />

echo '&lt;' . $inName . ' ' . join(' ', $attributes) . '&gt;';<br />

}<br />

266 | Chapter 11: XML<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!