Figure 11-2. Book details
We define a class, BookList, whose constructor
parses the XML file and builds a list of records. There are two
methods on a BookList that generate output from
that list of records. The show_menu( ) method
generates the book menu, and the show_book( )
method displays detailed information on a particular book.
Parsing the file involves keeping track of the record, which element
we're in, and which elements correspond to records
(book) and fields (title,
author, isbn, and
comment). The $record property
holds the current record as it's being built, and
$current_field holds the name of the field
we're currently processing (e.g.,
'title'). The $records property
is an array of all the records we've read so far.
Two associative arrays, $field_type and
$ends_record, tell us which elements correspond to
fields in a record and which closing element signals the end of a
record. Values in $field_type are either
1 or 2, corresponding to a
simple scalar field (e.g., title) or an array of
values (e.g., author) respectively. We initialize
those arrays in the constructor.
The handlers themselves are fairly straightforward. When we see the
start of an element, we work out whether it corresponds to a field
we're interested in. If it is, we set the
current_field property to be that field name so
when we see the character data (e.g., the title of the book) we know
which field it's the value for. When we get
character data, we add it to the appropriate field of the current
record if current_field says
we're in a field. When we see the end of an element,
we check to see if it's the end of a record—if
so, we add the current record to the array of completed records.