开发者

How not to rely on ordered XML in getting values for specific attributes

开发者 https://www.devze.com 2023-03-10 17:05 出处:网络
Given the following XML: $test = \'<response> <string key=\"status\">success</string>

Given the following 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>';

I have the following code, which works; for this example I only care for the value of sender_id and content of each array.

    $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>';
        }
    }

Result:

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

As I am relying on the ordering of the returned XML way too much ($message->string[1] and $message->string[0]). My question is, what is the correct way to echo out these values of the attributes without relying on the XML ordering?

I am aware of xPath, and have a working example, but it looks like a bowl of spaghetti code and if xPath is the answer, I would appreciate a working example.


You can access the attributes of a XML node as well:

$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;
                }
            }
        }
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消