<!--PHP编程实战-->
<!--XML -->
<!--14-8-->
<!--使用XPaht查找元素-->
<?php
error_reporting(E_ALL);
$xml = <<<THE_XML
<animal>
<type>dog</type>
<name>snoopy</name>
</animal>
THE_XML;
$xml_object = simplexml_load_string($xml);
$type = $xml_object->xpath("type");
foreach ($type as $t) {
echo $t . "<br/><br/>";
}
$xml_object = simplexml_load_string($xml);
$children = $xml_object->xpath("/animal/*");
foreach ($children as $element) {
echo $element->getName() . ": " . $element . "<br/>";
}
?>
知识点:
- 使用XPaht和XQuery查找嵌套的元素更加容易.
- XPath是SimpleXML库和PHP DOM库的组成部分.
- SimpleXML通过调用$simple_xml_object->xpath()来调用XPath
- DOM库中,通过创建一个DOMXPath对象,调用该对象的query方法来使用XPath.
$type = $xml_object->xpath("type");
选择type元素,返回一个SimpleXMLElement对象数组
$children = $xml_object->xpath("/animal/*");
选择animal的所有子元素,返回一个SimpleXMLElement对象数组