Application Example of XPath in PHP Operation XML

  • 2021-12-12 08:19:15
  • OfStack

This paper describes the application of XPath in PHP operating XML with examples. Share it for your reference, as follows:

XPath is the XML path language, which is a language used to determine the position of a part of an XML (a subset of the Standard Generalized Markup Language) document. Based on the tree structure of XML, XPath provides the ability to find nodes in the data structure tree. At first, XPath was proposed as a general grammar model between XPointer and XSLT. However, XPath was quickly adopted by developers as a small query language.

The core idea of XPath's design is to quickly locate (not loop through) the elements (or nodes) you need. PHP File After loading the xml file and creating the DOMDocument object, you can start creating the DOMXPath object.

The form of establishment is as follows:


$xpath = new DOMXPath($xmldoc);

After the DOMXPath object is created, you can start using the DOMXPath::query() Method to find the elements you need:


$item = $xpath->query("xpath Path expression ");// The return value is DOMNodList Object 

Example:

xml Documentation: words. xml


<?xml version="1.0" encoding="utf-8"?>
<words>
<word>
 <en>boy</en>
 <ch> Boy </ch>
</word>
<word>
 <en>girl</en>
 <ch> Girl </ch>
</word>
<word>
 <en>teacher</en>
 <ch> Teacher </ch>
</word>
<word>
 <en>beauty</en>
 <ch> Beauty </ch>
</word>
</words>

XPath Application: index. php


<?php
$xmldoc = new DOMDocument();
// Load file 
$xmldoc->load("words.xml");
// Use xpath Query 
$xpath = new DOMXPath($xmldoc);// Create DOMXPath Object 
$node_list = $xpath->query("/words/word/ch");// Query ch This element returns a value of DOMNodeList Object 
echo $node_list->item(0)->nodeValue;
?>

PS: Here are several online tools for xml operation for your reference:

Online XML/JSON interconversion tool:
http://tools.ofstack.com/code/xmljson

Online Formatting XML/Online Compression XML:
http://tools.ofstack.com/code/xmlformat

XML Online Compression/Formatting Tools:
http://tools.ofstack.com/code/xml_format_compress

XML code online formatting beautification tool:
http://tools.ofstack.com/code/xmlcodeformat

For more readers interested in PHP related contents, please check the special topics of this site: "Summary of PHP Operation Skills for XML File", "Encyclopedia of PHP Array (Array) Operation Skills", "Summary of php String (string) Usage", "Introduction to php Object-Oriented Programming", "Introduction to php+mysql Database Operation" and "Summary of php Common Database Operation Skills"

I hope this article is helpful to everyone's PHP programming.


Related articles: