當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


PHP DOMXPath evaluate()用法及代碼示例


DOMXPath::evaluate()函數是PHP中的內置函數,用於執行給定的XPath表達式,該表達式是為選擇一組節點而定義的模式。

用法:

mixed DOMXPath::evaluate( string $expression, 
          DOMNode $contextnode, bool $registerNodeNS )

參數:此函數接受上述和以下所述的三個參數:



  • $expression:它指定要執行的XPath表達式。
  • $contextnode (Optional):它指定用於執行相對XPath查詢的contextnode。默認情況下,查詢是相對於根元素的。
  • $registerNodeNS (Optional):它指定是否禁用上下文節點的自動注冊。

返回值:成功時此函數返回TRUE。

異常:該函數在出錯時拋出DOMXPathException。

下麵的示例說明了PHP中的DOMXPath::evaluate()函數:

範例1:

<?php 
   
// Create a new DOMDocument instance 
$document = new DOMDocument(); 
   
// Create a XML 
$xml = <<<XML 
<?xml version="1.0" encoding="utf-8"?> 
<bookstore> 
<book> 
  <title lang="en">GeeksforGeeks</title> 
  <price>400</price> 
</book> 
<book> 
  <title lang="en">Intro to XML</title> 
  <price>300</price> 
</book> 
</bookstore> 
XML; 
   
// Load the XML 
$document->loadXML($xml); 
   
// Create a new DOMXPath instance 
$xpath = new DOMXPath($document); 
   
// Get the 
$tbody = $document-> 
    getElementsByTagName('bookstore')->item(0); 
   
// Query to get the number of titles with lang  
// attribute "en" 
$query = 'count(//title[@lang=\'en\'])'; 
   
// Evaluate the query 
$entries = $xpath->evaluate($query, $tbody); 
echo "Number of elements with lang = \"en\":$entries\n"; 
?>

輸出:

Number of elements with lang = "en":2

範例2:

<?php 
  
// Create a new DOMDocument instance 
$document = new DOMDocument(); 
  
// Create a XML 
$xml = <<<XML 
<?xml version="1.0" encoding="utf-8"?> 
<GeeksforGeeks> 
  Keep Learning. 
</GeeksforGeeks> 
XML; 
  
// Load the XML 
$document->loadXML($xml); 
  
// Create a new DOMXPath instance 
$xpath = new DOMXPath($document); 
  
// Get the 
$tbody = $document-> 
getElementsByTagName('GeeksforGeeks')->item(0); 
  
// Get the element with name GeeksforGeeks 
$query = '//GeeksforGeeks'; 
  
// Evaluate the query 
$entries = $xpath->evaluate($query, $tbody); 
echo $entries[0]->nodeValue; 
?>

輸出:

Keep Learning.

參考: https://www.php.net/manual/en/domxpath.evaluate.php




相關用法


注:本文由純淨天空篩選整理自gurrrung大神的英文原創作品 PHP | DOMXPath evaluate() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。