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


PHP DOMXPath registerNamespace()用法及代码示例

DOMXPath::registerNamespace()函数是PHP中的内置函数,用于向DOMXPath对象注册名称空间URI和前缀。

用法:

bool DOMXPath::registerNamespace( string $prefix,
                    string $namespaceURI )

参数:该函数接受上述和以下描述的两个参数:



  • $prefix:它指定前缀。
  • $namespaceURI:它指定名称空间URI。

返回值:如果成功,则此函数返回TRUE;如果失败,则返回FALSE。

下面给出的程序说明了PHP中的DOMXPath::registerNamespace()函数:

程序1:

<?php 
  
// Create a new DOMDocument instance 
$document = new DOMDocument(); 
  
// Create a XML 
$xml = <<<XML 
<?xml version="1.0" encoding="UTF-8"?> 
<body xmlns="geeksforgeeks" > 
    <h1>Hello</h1> 
</body> 
XML; 
  
// Load the XML 
$document->loadXML($xml); 
  
// Create a new DOMXPath instance 
$xpath = new DOMXPath($document); 
  
// Register namespace with prefix 
// x and wrong URI 
$xpath->registerNamespace('x', 
              'geeksforgeeksnew'); 
  
// Use the prefix to create a query 
// to get the text in h1 
$query = '//x:body/x:h1/text()'; 
  
// Execute the query 
$entries = $xpath->evaluate($query); 
  
// Count the output 
echo count($entries) . "\n"; 
?>

输出:

0

程序2:

<?php 
  
// Create a new DOMDocument instance 
$document = new DOMDocument(); 
  
// Create a XML 
$xml = <<<XML 
<?xml version="1.0" encoding="UTF-8"?> 
<body xmlns="geeksforgeeks" > 
    <h1>Hello</h1> 
</body> 
XML; 
  
// Load the XML 
$document->loadXML($xml); 
  
// Create a new DOMXPath instance 
$xpath = new DOMXPath($document); 
  
// Register namespace with prefix x 
$xpath->registerNamespace('x', 
               'geeksforgeeks'); 
  
// Use the prefix to create a query 
// to get the text in h1 
$query = '//x:body/x:h1/text()'; 
  
// Execute the query 
$entries = $xpath->evaluate($query); 
  
// View the text 
echo $entries->item(0)->nodeValue . "\n"; 
?>

输出:

Hello

参考: https://www.php.net/manual/en/domxpath.registernamespace.php




相关用法


注:本文由纯净天空筛选整理自gurrrung大神的英文原创作品 PHP | DOMXPath registerNamespace() Function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。