<!--PHP编程实战-->
<!--XML -->
<!--14-9-->
<!--使用XPath匹配父与子-->
<?php
error_reporting(E_ALL);
$xml = <<<THE_XML
<animals>
<dog>
<name>snoopy</name>
<color>brown</color>
<breed>beagel cross</breed>
</dog>
<cat>
<name>teddy</name>
<color>brown</color>
<breed>tabby</breed>
</cat>
<dog>
<name>jade</name>
<color>black</color>
<breed>lab cross</breed>
</dog>
</animals>
THE_XML;
$xml_object = simplexml_load_string($xml);
$names = $xml_object->xpath("*/name");
foreach ($names as $element) {
$parent = $element->xpath("..");
$type = $parent[0]->getName();
echo "$element ($type)<br/>";
}
?>
使用XPath的*/name匹配<name>元素,而不考虑它是否被包含在<dog>或<cat>元素中.
使用查询..获取当前SimpleXMLElement的根.