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


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

DOMXPath::registerPhpFunctions()函數是PHP中的內置函數,用於啟用在XPath表達式中使用PHP函數的函數。

用法:

void DOMXPath::registerPhpFunctions( mixed $restrict )

參數:該函數接受可選的單個參數$restrict,該參數包含要限製的函數。



返回值:該函數不返回任何值。

下麵給出的程序說明了PHP中的DOMXPath::registerPhpFunctions()函數:

程序1:

<?php 
  
// Create a new DOMDocument instance 
$document = new DOMDocument(); 
  
// Create a XML 
$xml = <<<XML 
<?xml version="1.0" encoding="UTF-8"?> 
<books> 
    <book> 
        <title>FOO BAR</title> 
        <author>Mr. A</author> 
        <author>Mr. B</author> 
    </book> 
    <book> 
        <title>FOO BAZ</title> 
        <author>Mr. C</author> 
    </book> 
</books> 
XML; 
  
// Load the XML 
$document->loadXML($xml); 
  
// Create a new DOMXPath instance 
$xpath = new DOMXPath($document); 
  
// Register the php:namespace 
$xpath->registerNamespace("php", 
        "http://php.net/xpath"); 
  
// Register PHP functions 
$xpath->registerPHPFunctions(); 
  
// Use the PHP function to find 
// the books starting with FOO 
$query = '//book[php:functionString('
        . '"substr", title, 0, 3) = "FOO"]'; 
  
// Execute the query 
$entries = $xpath->evaluate($query); 
  
echo "Found $entries->length books"
        . " starting with 'FOO':\n"; 
foreach ($entries as $node) { 
    $title = $node->getElementsByTagName( 
                "title")->item(0)->nodeValue; 
    echo "<br>$title"; 
} 
?>

輸出:

Found 2 books starting with 'FOO':
FOO BAR
FOO BAZ

程序2:

<?php 
  
// Create a new DOMDocument instance 
$document = new DOMDocument(); 
   
// Create a XML 
$xml = <<<XML 
<?xml version="1.0" encoding="UTF-8"?> 
<books> 
    <book> 
        <title>FOO BAR</title> 
        <author>Mr. A</author> 
        <author>Mr. B</author> 
    </book> 
    <book> 
        <title>FOO BAZ</title> 
        <author>Mr. C</author> 
    </book> 
</books> 
XML; 
   
// Load the XML 
$document->loadXML($xml); 
   
// Create a new DOMXPath instance 
$xpath = new DOMXPath($document); 
   
// Register the php:namespace 
$xpath->registerNamespace("php", 
        "http://php.net/xpath"); 
   
// Register PHP functions 
$xpath->registerPHPFunctions(); 
   
// Use the manually created  
// PHP function in query 
$query = '//book[php:function('
        . '"has_multiple", author)]'; 
   
// Execute the query 
$entries = $xpath->evaluate($query); 
   
echo "Found $entries->length books "
        . "with multiple authors:\n"; 
  
foreach ($entries as $node) { 
    $title = $node->getElementsByTagName( 
            "title")->item(0)->nodeValue; 
    echo "<br>$title"; 
} 
   
function has_multiple($nodes) { 
      
    // Return true if more than 
    // one author is there 
    return count($nodes) > 1; 
} 
?>

輸出:

Found 1 books with multiple authors:
FOO BAR

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




相關用法


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