当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。