05.05.2013 Views

Programming PHP

Programming PHP

Programming PHP

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Figure 11-2. Book details<br />

comment). The $record property holds the current record as it’s being built, and<br />

$current_field holds the name of the field we’re currently processing (e.g., 'title').<br />

The $records property is an array of all the records we’ve read so far.<br />

Two associative arrays, $field_type and $ends_record, tell us which elements correspond<br />

to fields in a record and which closing element signals the end of a record.<br />

Values in $field_type are either 1 or 2, corresponding to a simple scalar field (e.g.,<br />

title) or an array of values (e.g., author) respectively. We initialize those arrays in<br />

the constructor.<br />

The handlers themselves are fairly straightforward. When we see the start of an element,<br />

we work out whether it corresponds to a field we’re interested in. If it is, we<br />

set the current_field property to be that field name so when we see the character<br />

data (e.g., the title of the book) we know which field it’s the value for. When we get<br />

character data, we add it to the appropriate field of the current record if current_<br />

field says we’re in a field. When we see the end of an element, we check to see if it’s<br />

the end of a record—if so, we add the current record to the array of completed<br />

records.<br />

One <strong>PHP</strong> script, given in Example 11-10, handles both the book menu and book<br />

details pages. The entries in the book menu link back to the URL for the menu, with<br />

a GET parameter identifying the ISBN of the book whose details are to be displayed.<br />

Example 11-10. bookparse.xml<br />

<br />

My Library<br />

<br />

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

Saved successfully!

Ooh no, something went wrong!