📜  PHP | SimpleXMLElement XPath()函数

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

PHP | SimpleXMLElement XPath()函数

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

SimpleXMLElement::xpath()函数是PHP中的一个内置函数,它在 XML 文档上运行 XPath 查询。

句法:

SimpleXMLElement::xpath( $path )

参数:此函数接受所需的单个参数$path 。用于指定 XML 文档的 XPath 路径。

返回值:成功时返回 SimpleXMLElements 数组,失败时返回 False。

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

例子:


    12345
    Geeks123
    GeeksforGeeks
    +91-XXXXXXXXXX
    
        Noida India
    

XML;
  
// Loading string as simple xml object
$xml = simplexml_load_string($user);
  
// Retrieving xpaths
$result = $xml->xpath("username");
  
// Printing output
print_r($result);
   
?>
输出:
Array
(
    [0] => SimpleXMLElement Object
        (
            [0] => Geeks123
        )

)

示例 2:



    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

示例 3:


    
        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');
  
// Printing 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.xpath。 PHP