如何在获取特定属性的值时不依赖有序XML

时间:2011-06-07 03:20:45

标签: php xml

给出以下XML:

$test = '<response>
  <string key="status">success</string>
  <string key="count">3</string>
  <array key="results">
    <array key="1">
       <string key="content">Message content 1</string>
       <string key="garbage">I_dont_care</string>
       <string key="sender_id">100</string>
       <string key="more_garbage">more_stuffs</string>
    </array>
    <array key="2">
       <string key="content">Message content 2</string>
       <string key="garbage">I_dont_care</string>
       <string key="sender_id">200</string>
       <string key="more_garbage">more_stuffs</string>
    </array>
    <array key="3">
       <string key="content">Message content 3</string>
       <string key="garbage">I_dont_care</string>
       <string key="sender_id">300</string>
       <string key="more_garbage">more_stuffs</string>
    </array>
  </array>
</response>';

我有以下代码,有效;对于这个例子,我只关心sender_id的值和每个数组的内容。

    $xml = simplexml_load_string($test);

    $status = $xml->string[0];
    if($status == 'success')
    {
        foreach($xml->array[0] as $message)
        {
            $sender_id = $message->string[1] . '<br>';
            $content = $message->string[0];

            echo 'Sender ID: ' . $sender_id;
            echo 'Message content: ' . $content;
            print '<hr>';
        }
    }

结果:

Sender ID: 100
Message content: Message content 1
Sender ID: 200
Message content: Message content 2
Sender ID: 300
Message content: Message content 2

因为我依赖于返回的XML方式的排序过多($ message-&gt; string [1]和$ message-&gt; string [0])。我的问题是,在不依赖XML排序的情况下回显这些属性值的正确方法是什么?

我知道xPath,并且有一个工作示例,但它看起来像一碗意大利面条代码,如果xPath是答案,我会很感激一个有效的例子。

1 个答案:

答案 0 :(得分:0)

您也可以访问XML节点的属性:

$status = $xml->string[0];
if($status == 'success') {
    foreach($xml->array[0] as $message) {
        foreach($message->string as $string){
            foreach($string->attributes() as $attribute){
                switch($attribute){
                    case 'sender':
                        echo 'Sender ID:'.(string)$string;
                    break;
                    case 'content':
                        echo 'Message Content:'.(string)$string;
                    break;
                }
            }
        }
    }
}