-5

私はPHPの初心者です。XMLファイルがあります。name属性値を持つノードを検索し、その子ノードのテキスト値を変数に格納したいと考えています。PHPコードでそれを行うにはどうすればよいですか。

例。

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

これは私が持っている XML ファイルです。この XML ファイルの親ノード<Server>には多くの子ノードが含まれます。ここでは、キーワード(属性である) で検索するときに、ノード(ユーザー) と(パスワード) 内のデータを 2 つの異なる変数に<Server1>取得したいと考えています。ノードの値)。このための素敵な PHP コードを教えてください。<username><password>10.3.0.5idipaddress

4

1 に答える 1

0

私が理解しているように、あなたの質問をもう一度述べることから始めましょう: サーバー要素の複数の子があり、それぞれに 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;
    }
}
?>
于 2013-04-26T06:19:36.127 に答える