Use of Xpath in PHP Fahmida Yesmin Haniwriter
Use of Xpath in PHP Fahmida Yesmin Haniwriter
Excerpt: XML document is used to store a small amount of data, and sometimes it is required to read the
particular content of XML document based on the path value using PHP script. xpath() function is used to
parse the content of an XML document. In this article Use of xpath() in PHP is reviewed.
Permalink: Use-xpath()-PHP
Category: php
XML document is used to store a small amount of data, and sometimes it is required to read the
particular content of XML document based on the path value using PHP script. xpath() function
is used to parse the content of an XML document. This function can be used by using
simplexml_load_file() function or by creating the object of SimpleXMLElement class. The
xpath() function can be used to read the particular XML node values shown in this tutorial.
Syntax:
The syntax of the xpath() function is given below.
array xpath(string $path)
This function has one argument that takes a path value, and if the path exists in any node of the
XML document, then the value of the node will be returned as an array. Different uses of this
function have explained in the next part of this tutorial.
<PRODUCTS>
<PRODUCT category="Monitor">
<ID>MN-56345</ID>
<BRAND>DELL</BRAND>
<NAME>15 inches Dell Monitor</NAME>
<PRICE>700</PRICE>
</PRODUCT>
<PRODUCT category="HDD">
<ID>HD-34278</ID>
<BRAND>SAMSUNG</BRAND>
<NAME>1 TB Samsung HDD</NAME>
<PRICE>520</PRICE>
</PRODUCT>
<PRODUCT category="Mouse">
<ID>MS-67457</ID>
<BRAND>LOGITECH</BRAND>
<NAME>Logitech Wireless Mouse</NAME>
<PRICE>100</PRICE>
</PRODUCT>
<PRODUCT category="Monitor">
<ID>MN-76453</ID>
<BRAND>HP</BRAND>
<NAME>14 inches HP Monitor</NAME>
<PRICE>750</PRICE>
</PRODUCT>
</PRODUCTS>
Output:
The following output will appear after running the script from the server.
<?php
Output:
The following output will appear after running the script from the server.
<?php
$xml_data = <<<XML
<customers>
<customer department="HR">
<name>Md. Mahbub</name>
<email>[email protected]</email>
</customer>
<customer department="Sales">
<name>Farhana Zaman</name>
<email>[email protected]</email>
</customer>
</customers>
XML;
Output:
The following output will appear after running the script from the server.
Conclusion:
Two different ways of using the xpath() function to read the XML document's node values based
on the specific path or the path with the condition or the path with attribute value have been
explained in this tutorial by using multiple examples.