PHP - SimpleXMLElement::xpath() 函式



定義和用法

XML 是一種用於在網路上共享資料的標記語言,XML 既可供人類閱讀,也可供機器讀取。SimpleXMLElement 類在 PHP 中表示 XML 文件。

SimpleXMLElement::xpath() 函式接受一個字串值作為引數,該引數表示一個 XPath 表示式,搜尋並檢索給定路徑下 XML 節點的子節點。

語法

SimpleXMLElement::xpath($path);

引數

序號 引數及說明
1

path (必填)

這是一個表示 XPath 表示式的字串值。

返回值

如果成功,此函式返回一個 SimpleXMLElement 物件陣列,表示節點;如果失敗,則返回 FALSE。

PHP 版本

此函式首次在 PHP 5 版本中引入,並在所有後續版本中均有效。

示例

以下示例演示了 SimpleXMLElement::xpath() 函式的用法。

<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> 

這將產生以下結果:

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

示例

以下是此函式的另一個示例,我們嘗試載入 XML 檔案的內容並檢索指定路徑的內容:

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>

這將產生以下輸出:

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