The application example of XPath in Php+xml programming _php skills

Source: Internet
Author: User
Tags xpath

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.