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


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


DOMXPath::__construct()函數是PHP中的一個內置函數,用於創建DOMXPath的實例。

用法:

bool DOMXPath::__construct( DOMDocument $doc )

參數:此函數接受單個參數$doc,該參數包含與DOMXPath關聯的DOMDocument。



以下示例說明了PHP中的DOMXPath::__construct()函數:

範例1:

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

輸出:

Hello World

範例2:

<?php 
  
// Create a new DOMDocument instance 
$document = new DOMDocument(); 
  
// Create a XML 
$xml = <<<XML 
<?xml version="1.0" encoding="utf-8"?> 
<root> 
    <content> 
        First 
    </content> 
    <content> 
        Second 
    </content> 
    <content> 
        Third 
    </content> 
</root> 
XML; 
  
// Load the XML 
$document->loadXML($xml); 
  
// Create a new DOMXPath instance 
$xpath = new DOMXPath($document); 
  
// Get the root element 
$tbody = $document-> 
getElementsByTagName('root')->item(0); 
  
// Count the number of element with  
// name content 
$query = 'count(//content)'; 
  
// Evaluate the query 
$entries = $xpath->evaluate($query, $tbody); 
echo $entries; 
?>

輸出:

3

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




相關用法


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