📜  PHP | SimpleXMLElement registerXPathNamespace()函数

📅  最后修改于: 2022-05-13 01:56:43.723000             🧑  作者: Mango

PHP | SimpleXMLElement registerXPathNamespace()函数

先决条件:阅读 XML 基础知识

SimpleXMLElement::registerXPathNamespace()函数是PHP中的一个内置函数,用于为接下来在 SimpleXML 对象中执行的 XPath 查询创建命名空间上下文。

句法:

bool SimpleXMLElement::registerXPathNamespace( $prefix, $namespace )

参数:该函数接受上面提到的两个参数,如下所述:

  • $prefix:必填参数。它在 $namespace 中给定的命名空间的 XPath 查询中使用。
  • $namespace: :它是必需的参数。它指定 XPath 查询的命名空间。

返回值:成功时返回 True,失败时返回 False。

注意:此函数在PHP 5.2.0 及更新版本可用。

下面的程序说明了PHP中的 SimpleXMLElement::registerXPathNamespace()函数:

方案一:



    12345
    Geeks123
    GeeksforGeeks
    +91-XXXXXXXXXX
    
        Noida India
    

  

    15980
    Geeks54321
    Geeks
    +91-XXXXXXXXXX
    
        Noida India
    


XML;
  
// Loading string as simple xml object
$xml = simplexml_load_string($user);
  
// Registering Xpath namespace
$xml->registerXPathNamespace('u', 'http://geeksforgeeks.org/user');
  
// Retrieving xpaths
$result = $xml->xpath('//u:id');
  
// Printing output
foreach ($result as $id) {
    echo $id . "
"; }    ?>
输出:
1234515980

方案二:


    
        12345
        rakesh123
        Rakesh
        Kumar
        +91-XXXXXXXXXX
        Noida India
    
      
    
        57833
        man123
        Manjeet
        Singh
        +91-XXXXXXXXXX
        Kolkata, India
    
      
    
        98944
        ak98
        Ak
        Singh
        +91-XXXXXXXXXX
        Noida India
    

XML;
  
// Loading string as simple xml object
$xml = simplexml_load_string($user);
  
// Registering xpath namespace
$xml->registerXPathNamespace('u', 'http://geeksforgeeks.org/user');
$xml->registerXPathNamespace('un', 'http://geeksforgeeks.org/user/name');
  
// Retrieving xpaths
$result = $xml->xpath('//u:id');
$result_f_name = $xml->xpath('//un:firstname');
$result_l_name = $xml->xpath('//un:lastname');
  
// Displaying output
foreach ($result as $id) {
    echo $id . "
"; } foreach ($result_f_name as $f_name) {     echo $f_name . "
"; } foreach ($result_l_name as $l_name) {     echo $l_name . "
"; }    ?>
输出:
123455783398944RakeshManjeetAkKumarSinghSingh

参考: https://www. PHP.net/manual/en/simplexmlelement.registerxpathnamespace。 PHP