XML and PHP [Electronic resources] نسخه متنی

اینجــــا یک کتابخانه دیجیتالی است

با بیش از 100000 منبع الکترونیکی رایگان به زبان فارسی ، عربی و انگلیسی

XML and PHP [Electronic resources] - نسخه متنی

Vikram Vaswani

| نمايش فراداده ، افزودن یک نقد و بررسی
افزودن به کتابخانه شخصی
ارسال به دوستان
جستجو در متن کتاب
بیشتر
تنظیمات قلم

فونت

اندازه قلم

+ - پیش فرض

حالت نمایش

روز نیمروز شب
جستجو در لغت نامه
بیشتر
لیست موضوعات
توضیحات
افزودن یادداشت جدید















Traversing the DOM with PHP's XPath Classes



The DOM classes discussed in the previous section are more than adequate for most common tasks, but getting used to them can take awhile.


Additionally, for long and complex documents containing a large number of elements and/or levels, progressing from node to node in an iterative manner can often be tedious.You can use a recursive function to simplify the process, but you'll still have to write a fair amount of code to create and manipulate node collections, which are at different levels of the tree.


It's precisely to simplify this process that PHP also comes with a couple of XPath classes. XPath, as you may already know, is an addressing mechanism for XML documents, designed to allow XML document authors to quickly access node collections on the basis of both location and condition.


A discussion of XPath is beyond the scope of this book, so I'll assume that you already know the basics of axes, predicates, and node tests. In case you don't, you might want to brush up on the basics before proceeding with this section. Go to the companion web site for this book http://www.xmlphp.com/ or http://www.newriders.com) to find a list of reference material to get you started.



XPathContext and XPathObject Classes



PHP's XPath classes add flexibility to the DOM parser by freeing developers from the standard parent-child paradigm when constructing node collections.The XPath classes allow developers to quickly build node collections matching specific criteriafor example, every third element or every element containing the attribute shape=square with scant regard for their position in the hierarchical document tree.


The XPathContext class is used to set up a context for all XPath evaluations, and is created by a call to the xpath_new_context() function. This function must be passed a reference to a DomDocument object. For example:



<?php
// create a DomDocument object
$doc = xmldoc($xml_string);
// create an XPath context
$xpath = $doc->xpath_new_context();
?>


If you think this doesn't look very interesting, you're rightit's not. The XPathContext object merely sets up a context for all future XPath evaluations. These XPath evaluations usually result in instances of the XPathObject class, which are far more interesting.


An instance of the XPathObject class may be created with a call to the xpath_eval() method of the XPathContext object, which requires an XPath address for evaluation. If the XPath evaluates successfully, xpath_eval() returns an instance of the XPathObject class containing a collection of nodes matching the specified XPath expression. Take a look at Listing 3.11, which uses an XPath address to isolate all the vegetable elements in the document:


Listing 3.11 Creating Node Collections with XPath



<?php
// XML data
$xml_string = "<?xml version='1.0'?>
<sentence>What a wonderful profusion of colors and smells in the market
<vegetable color='green'>cabbages</vegetable>,
<vegetable color='red'>tomatoes</vegetable>,
<fruit color='green'>apples</fruit>,
<vegetable color='purple'>aubergines</vegetable>,
<fruit color='yellow'>bananas</fruit>
</sentence>";
$doc = xmldoc($xml_string);
// create an XPath context
$xpath = $doc->xpath_new_context();
// get all the "vegetable" elements
$vegetables = $xpath->xpath_eval("//vegetable");
// uncomment the next line to see the node collection
// print_r($vegetables);
?>


When you examine the structure of the XPathObject object instance with print_r(), here's what you'll see:



XPathObject Object
(
[type] => 1
[nodeset] => Array
(
[0] => DomElement Object
(
[type] => 1
[tagname] => vegetable
)
[1] => DomElement Object
(
[type] => 1
[tagname] => vegetable
)
[2] => DomElement Object
(
[type] => 1
[tagname] => vegetable
)
)
)


As you can see, the object contains an array of DomElement objects, representing the element nodes matching the XPath expression. These DomElement objects can now be accessed and manipulated using standard class methods and properties.



A Composite Example



In order to demonstrate just how powerful XPath can be, consider the following situation. In a research project conducted to study the effect of temperature on bacterial culture growth, researchers publish their findings as XML data. Listing 3.12 contains a sample of this data.


Listing 3.12 A Compilation of Experiment Readings (data.xml)



<?xml version="1.0"?>
<project id="49">
<!-- data for 3 cultures: Alpha, Beta and
Gamma, tested at temperatures ranging from
10C to 50C -->
<!-- readings indicate cell counts 4 hours
after start of experiment -->
<record>
<culture>Alpha</culture>
<temperature>10</temperature>
<reading>25000</reading>
</record>
<record>
<culture>Beta</culture>
<temperature>10</temperature>
<reading>4000</reading>
</record>
<record>
<culture>Alpha</culture>
<temperature>10</temperature>
<reading>23494</reading>
</record>
<record>
<culture>Alpha</culture>
<temperature>20</temperature>
<reading>21099</reading>
</record>
<record>
<culture>Gamma</culture>
<temperature>40</temperature>
<reading>768</reading>
</record>
<record>
<culture>Gamma</culture>
<temperature>10</temperature>
<reading>900</reading>
</record>
<!-- snip -->
</project>


It now becomes necessary to compile this raw data into an easily understandable table so that the results can be analyzed. Ideally, what is required is a 2x2 table displaying the temperature scale on the Y-axis and the culture type on the X-axis.The intersection of the two axes should be an average of all readings made for that culture at that temperature.


With XPath, this is a snap to accomplish. Listing 3.13 demonstrates the script.


Listing 3.13 Creating Node Collections with XPath



<html>
<head>
<basefont face="Arial">
</head>
<body bgcolor="white">
<?php
// XML file
$xml_file = "data.xml";
// parse document
$doc = xmldocfile($xml_file) or die("Could not read file!");
// create arrays to hold culture/temperature list
$cultures = array();
$temperatures = array();
// create XPath context
$xpath = $doc->xpath_new_context();
// get a list of "culture" nodes
$obj = $xpath->xpath_eval("//culture");
$nodeset = $obj->nodeset;
// ...and create an array containing
// the names of all available cultures
for ($x=0; $x<sizeof($nodeset); $x++)
{
$children = $nodeset[$x]->children();
$cultures[] = $children[0]->content;
}
// strip out duplicates
$cultures = array_unique($cultures);
// do the same thing for temperature points
$obj = $xpath->xpath_eval("//temperature");
$nodeset = $obj->nodeset;
for ($x=0; $x<sizeof($nodeset); $x++)
{
$children = $nodeset[$x]->children();
$temperatures[] = $children[0]->content;
}
$temperatures = array_unique($temperatures);
// sort both arrays
natsort($temperatures);
natsort($cultures);
?>
<table border="1" cellspacing="5" cellpadding="5">
<tr>
<td>&nbsp;</td>
<?php
// first row of table, print culture names
foreach($cultures as $c)
{
echo "<td>$c</td>";
}
?>
</tr>
<?php
foreach($temperatures as $t)
{
// create as many rows as there are temperature points
echo "<tr>";
echo "<td>$t</td>";
// for each intersection (culture, temperature)
// print average of available readings
foreach($cultures as $c)
{
echo "<td>" . intersection($t, $c) . "</td>";
}
echo "</tr>";
}
?>
</table>
<?php
// this function collects all readings for
// a particular culture/temperature
// totals them and averages them
function intersection($temperature, $culture)
{
// get a reference to the XPath context
global $xpath;
// set up variables to hold total and frequency
$total = 0;
$count=0;
// get a list of "reading" nodes
// for records with culture c and temperature t
$obj = $xpath->xpath_eval
("//record[culture='" . $culture . "' and temperature='" .
$temperature . "']/reading");
// if XPath evaluation successful
if ($obj)
{
$nodeset = $obj->nodeset;
// iterate through nodeset
if (is_array($nodeset))
{
// add the readings
foreach ($nodeset as $reading)
{
$children = $reading->children();
$total += $children[0]->content;
$count++;
}
}
}
// and then average them
if ($count > 0)
{
return $total/$count;
}
return 0;
}
?>
</body>
</html>


I've used three different XPath expressions here. The first two are used to create a list of available cultures and temperature points; these are required for the row and column headings of the table. The third XPath returns a list of nodes matching a specific culture and temperature. Now, all I need to do is add the readings associated with each of these nodes to reach a total number, and divide that total number by the number of nodes (readings) to obtain an average cell count.


Figure 3.3 shows what the output looks like.



Figure 3.3. Statistical analysis with Xpath.






This kind of thing comes in particularly handy when you need to perform statistical analysis of sampling data; it provides a simple and easy way to bring together different elements of each sample, perform calculations on these elements, and relate them to each other in two or three dimensions. XPath's conditional expressions are a boon herealthough you can certainly do the same thing without XPath (and I encourage you to try, just so you have a better understanding of the difference), the process would be far more tedious.




/ 84