This article illustrates the application of XPath in Php+xml programming. Share to everyone for your reference. Specifically as follows:
The core idea of XPath design: quickly navigate to the elements (or nodes) you need. After loading the XML file and creating the DOMDocument object, the PHP file can begin building the Domxpath object. The following forms are established:
Copy Code code as follows:
$xpath = new Domxpath ($xmldoc);
Once you've created the Domxpath object, you can start using the Domxpath::query () method to find the elements you need:
Copy Code code as follows:
$item = $xpath->query ("XPath path expression");//return value is Domnodlist object
Instance:
XML Document: Words.xml
Copy Code code as follows:
<?xml version= "1.0" encoding= "Utf-8"?>
<words>
<word>
<en>boy</en>
<ch> Boy </ch>
</word>
<word>
<en>girl</en>
<ch> Girls </ch>
</word>
<word>
<en>teacher</en>
<ch> Teacher </ch>
</word>
<word>
<en>beauty</en>
<ch> Beauty </ch>
</word>
</words>
XPath applications: index.php
Copy Code code as follows:
<?php
$xmldoc = new DOMDocument ();
Loading files
$xmldoc->load ("Words.xml");
Using XPath queries
$xpath = new Domxpath ($xmldoc);//Create Domxpath Object
$node _list = $xpath->query ("/words/word/ch");//Query ch This element, the return value is Domnodelist object
echo $node _list->item (0)->nodevalue;
?>
I hope this article will help you with the Php+xml program design.