• PHP Video Tutorials

PHP - SimpleXMLElement::xpath() Function



Definition and Usage

XML is a mark-up language to share the data across the web, XML is for both human read-able and machine read-able. The SimpleXMLElement class represents an XML document in PHP.

The SimpleXMLElement::xpath() function accepts a strng value as a parameter representing an xpath, searches and retrives the children of the XML node at the given path.

Syntax

SimpleXMLElement::xpath($path);

Parameters

Sr.No Parameter & Description
1

path (Mandatory)

This is a string value representing an XPath.

Return Values

This function returns an array of objects of type SimpleXMLElement representing the nodes in case of success and, FALSE in case of failure.

PHP Version

This function was first introduced in PHP Version 5 and works in all the later versions.

Example

Following example demonstrates the usage of the SimpleXMLElement::xpath() function.

<html>
   <head>
      <body>
         <?php
            $xmlstr = "<?xml version='1.0' standalone='yes'?>
            <Tutorial>
               <Name>JavaFX</Name>
               <Pages>535</Pages>
               <Author>Krishna</Author>
               <Version>11</Version>
            </Tutorial>";
            $xml = new SimpleXMLElement($xmlstr);
            $node = $xml->xpath('/Tutorial/Author');
            print_r($node);	  
         ?>      
      </body>
   </head>   
</html> 

This will produce following result −

Array ( [0] => SimpleXMLElement Object ( [0] => Krishna ) )

Example

Following is another example of this function where we are trying to load the contents of an XML file and retrieve the contents of a specified path −

data.xml

<?xml version="1.0" encoding="utf-8"?>
<Tutorials>
   <Tutorial>
      <Name>JavaFX</Name>
      <Pages>535</Pages>
      <Author>Krishna</Author>
      <Version>11</Version>
   </Tutorial>

   <Tutorial>
      <Name>CoffeeScript</Name>
      <Pages>235</Pages>
      <Author>Kasyap</Author>
      <Version>2.5.1</Version>
   </Tutorial>
   
   <Tutorial>
      <Name>OpenCV</Name>
      <Pages>150</Pages>
      <Author>Maruti</Author>
      <Version>3.0</Version>
   </Tutorial>
</Tutorials>

Sample.htm:

<html>
   <head>      
      <body>         
         <?php
            $doc = new DOMDocument;
            $xml = simplexml_load_file("data.xml");
            //file to SimpleXMLElement 
            $xml = simplexml_import_dom($xml);
		
            $node = $xml->xpath('/Tutorials/Tutorial/Name');
            print_r($node);
         ?>
      </body>
   </head>
</html>

This will produce the following output −

Array ( 
   [0] => SimpleXMLElement Object ( [0] => JavaFX ) 
   [1] => SimpleXMLElement Object ( [0] => CoffeeScript ) 
   [2] => SimpleXMLElement Object ( [0] => OpenCV ) 
)
php_function_reference.htm
Advertisements