开发者

How-to parse XML key:value pair

开发者 https://www.devze.com 2023-03-09 20:21 出处:网络
I have a clients server returning the following (strange) XML response; how do I access each key:value pair?

I have a clients server returning the following (strange) XML response; how do I access each key:value pair?

$xml = '<?xml version="1.0"?>
  <response>
    <string key="__status">success</string>
    <string key="id">1000</string>
    <string key="m开发者_如何学运维ask">9999</string>
</response>';

I was hoping that the following would work, but it appears not.

$test = new SimpleXMLElement($xml);
echo "Mask: " . $xml->response->mask; // Mask: 9999


If you want a specific element, you can use XPath:

$matches = $test->xpath('//string[@key="mask"]');

(this requires PHP 5.2)

This would give you:

Array
(
    [0] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [key] => mask
                )

            [0] => 9999
        )
)   

If you want all elements, you have to iterate over all string elements and access their text and key attribute:

$items = array();

foreach($test->string as $item) {
    $items[(string) $item->attributes()->key] = (string) $item;
}

gives:

Array
(
    [__status] => success
    [id] => 1000
    [mask] => 9999
) 


<pre>
<?php
$xml = '<?xml version="1.0"?>
  <response>
    <string key="__status">success</string>
    <string key="id">1000</string>
    <string key="mask">9999</string>
</response>';

$test = new SimpleXMLElement($xml);
echo "Mask = ".$test->string[2];
?>
</pre>

Here is the working code.


if my memory server me right simplexml is extension. Are you sure you installed it? BTW, simplexml was added in PHP 5.0, so make sure you are not running lower version

0

精彩评论

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

关注公众号