【问题标题】:Search through XML using PHP [duplicate]使用 PHP 搜索 XML [重复]
【发布时间】:2013-04-20 05:14:33
【问题描述】:

我是 PHP 的初学者。我有一个 XML 文件。我想搜索具有name 属性值的节点,并将其子节点的文本值存储到变量中。我怎样才能用 PHP 代码做到这一点。

示例。

<Server>
<Server1>
<ipaddress name="10.3.0.5">
<username>user</username>
<password>password</password>
</ipaddress>
</Server1>
</Server>

这是我拥有的 XML 文件。此 XML 文件中的父节点 <Server> 将包含许多 <Server1> 子节点。在这里,我想获取节点 <username>(用户)和 <password> 内的数据(密码)在使用关键字10.3.0.5(即节点ipaddress 的id 属性值)搜索时分成两个不同的变量。请为此提供一个不错的 PHP 代码。

【问题讨论】:

标签: php xml


【解决方案1】:

让我首先按照我的理解重申您的问题:如果您有几个服务器元素的孩子,每个孩子都有一个由 ip 地址标识的孩子,您如何提取给定 ip 的用户名和密码地址?

如果这确实是你的问题,我相信下面的解决方案可以为你工作:

<?php

// Declare which ip address you want to get more information about
$ip_address_to_find = '10.3.0.5';

// Full xml string that you need to search through (this is an imagined example. The last element in this xml is the one we're going to find)
$xml_string = '
<Server>
      <Server1>
             <ipaddress name="10.3.0.1">
                         <username>username1</username>
                         <password>password1</password>
             </ipaddress>
      </Server1>
      <Server2>
             <ipaddress name="10.3.0.2">
                         <username>username2</username>
                         <password>password2</password>
             </ipaddress>
      </Server2>
      <Server3>
             <ipaddress name="10.3.0.3">
                         <username>username3</username>
                         <password>password3</password>
             </ipaddress>
      </Server3>
      <Server4>
             <ipaddress name="10.3.0.4">
                         <username>username4</username>
                         <password>password4</password>
             </ipaddress>
      </Server4>
      <Server5>
             <ipaddress name="10.3.0.5">
                         <username>username5</username>
                         <password>password5</password>
             </ipaddress>
      </Server5>
</Server>';

// Use simplexml to make an object out of it
$xml_object = simplexml_load_string($xml_string);

// Cycle through the object until you find a match
foreach($xml_object as $server){
    if($server->ipaddress->attributes()->name == $ip_address_to_find ){
        $username = $server->ipaddress->username;
        $password = $server->ipaddress->password;
        // Now use $username and $password however you want
        // for example:
        echo 'For the server with IP address: '.$ip_address_to_find.', the username is: '.$username.', and the password is: '.$password.'.'.PHP_EOL;
    }
}
?>

【讨论】:

  • 但是我有一个单独的 XML 文件。
  • 那么你只需使用 file_get_contents 或 curl,或者任何你想检索 xml 的方式。它最终仍然是一个字符串,分配给一个变量,此时您可以按照我上面指出的那样搜索它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多