Application Example of xpath in php + xml Programming

Source: Internet
Author: User
This article mainly introduces the application of xpath in php + xml programming. The example analyzes the functions, definitions, and usage skills of xpath. For more information, see

This article mainly introduces the application of xpath in php + xml programming. The example analyzes the functions, definitions, and usage skills of xpath. For more information, see

This article describes the application of xpath in php + xml programming. Share it with you for your reference. The details are as follows:

The core idea of xpath design: Quickly locate the elements (or nodes) you need ). After the PHP file loads the xml file and creates a DOMDocument object, you can create a DOMXPath object. The procedure is as follows:

The Code is as follows:

$ Xpath = new DOMXPath ($ xmldoc );

After the DOMXPath object is created, you can use the DOMXPath: query () method to find the elements you need:

The Code is as follows:

$ Item = $ xpath-> query ("xpath path expression"); // the return value is a DOMNodList object.

Instance:

Xml document: words. xml

The Code is as follows:

<? Xml version = "1.0" encoding = "UTF-8"?>


Boy
Boy


Girl
Girl


Teacher
Instructor


Beauty
Beauty

Xpath application: index. php

The Code is as follows:

<? Php
$ Xmldoc = new DOMDocument ();
// Load the file
$ Xmldoc-> load ("words. xml ");
// Query using xpath
$ Xpath = new DOMXPath ($ xmldoc); // create a DOMXPath object
$ Node_list = $ xpath-> query ("/words/word/ch"); // query the ch element. The returned value is the DOMNodeList object.
Echo $ node_list-> item (0)-> nodeValue;
?>

I hope this article will help you with php + XML programming.

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.