The DOM Model Page 37
March 15, 2002
This code does output the contents of the XML file to the
browser, but it's not in the format that we want. Notice how
each Travelpackage element is followed by the values of the
attributes of its elements, as is the case with Package. What
this indicates is that the nesting of the elements isn't
maintained when the tree is either built or parsed:
We have to do a little more work to get the HTML that we want.
The beginning of this file is the same as the previous example.
We instantiate a new XML object called $doc and instantiate a
new context for XPath called $context:
<html>
<head>
<title>DOM Travel Packages</title>
</head>
<body>
<h1>Travel Packages</h1>
<table>
<?php
$doc = xmldoc(join("", file("travel.xml")));
$context = xpath_new_context($doc);
$root = $doc->root();
We will use the node Travelpackage as the conceptual row
separator for this document. There is an attribute name for
Travelpackage. The value of this attribute is used to search for
each group of nodes that need to be pulled from the DOM tree. We
create an array that contains all the child nodes of
Travelpackage name="x" together. We'll use a for loop to step
through the array and use the array as a value in the XPath
statement:
$var = array("a","b");
for ($x = 0; $x < count($var); $x++) {
$path = xpath_eval($context,
"//Travelpackage[@name=\"$var[$x]\"]/Country_name");
$tmpArray = $path->nodeset;
This first XPath statement
//Travelpackage[@name=\"$var[$x]\"]/Country_name will be parsed
to: //Travelpackage[@name="a"]/Country_name during the first
pass of the for loop. All the nodes named Country_name that are
children of Travelpackage where name="a" will be stored in
$tmpArray. This xpath_eval statement could have been wrapped in
a conditional if statement to improve error handling, as is
shown in the previous code sample:
echo("<tr><td>");
echo($tmpArray[0]->name);
echo("</td><td><a href=\"#\">");
echo($tmpArray[0]->content);
echo("</a></td></tr>\n");
We've collected some node information, and now we print it out
into a table. The array $tmpArray may have more than just name
or content. Depending on the XML document, it will also have
type, node, attributes, comments, and/or processing
instructions. If we were to do a print_r($tmpArray), we would
see the array elements. Here's what they look like with this
code and XML document:
Array
(
[0] => DomNode Object
(
[type] => 1
[name] => Country_name
[content] => Cuba
[node] => Resource id #5
)
)
So we explicitly print out just the name and content elements
from the array. We can add any kind of formatting we want so our
HTML looks the way we want it.
The DOM Model Page 36
Professional PHP4 Programming
The DOM Model Page 38
|