我正在尝试使用simpleXML查找属性

时间:2013-02-05 21:30:28

标签: php simplexml

我有一个simpleXML输出:

SimpleXMLElement Object
(
    [@attributes] => Array
    (
        [version] => 2
    )
    [currentTime] => 2013-02-05 21:26:09
    [result] => SimpleXMLElement Object
    (
        [rowset] => SimpleXMLElement Object
        (
            [@attributes] => Array
            (
                [name] => characters
                [key] => characterID
                [columns] => name,characterID,corporationName,corporationID
            )
            [row] => Array
            (
                [0] => SimpleXMLElement Object
                (
                    [@attributes] => Array
                    (
                        [name] => Wrytha Cy
                        [characterID] => 209668693
                        [corporationName] => Deep Core Mining Inc.
                        [corporationID] => 1000006
                    )
                )
                [1] => SimpleXMLElement Object
                (
                    [@attributes] => Array
                    (
                        [name] => Eve Mae
                        [characterID] => 624980803
                        [corporationName] => Viziam
                        [corporationID] => 1000066
                    )
                )
                [2] => SimpleXMLElement Object
                (
                    [@attributes] => Array
                    (
                        [name] => Wrytha
                        [characterID] => 709227913
                        [corporationName] => The Flying Tigers
                        [corporationID] => 669350666
                    )
                )
            )
        )
    )
    [cachedUntil] => 2013-02-05 21:35:04
)

我想循环使用我的php循环并获取“name”和“characterID”。我尝试过类似的东西:

    $simpleXML = simplexml_load_string($xml); 

    foreach ($simpleXML->result->rowset->row as $row) {
        print_r($row);
        $name = $row['@attributes']['name'];
        echo $name.'<br>';
    }

但是没有设置$ name。这将是一件简单的事情,只是没有在我的仓促和第一次使用simpleXML时看到它。

1 个答案:

答案 0 :(得分:0)

使用语法$element['attribute_name']访问属性,因此在您的情况下,您需要$row['name']

重要的是要记住SimpleXML对象有点神奇 - $element->child$element_list[0]$element['foo']语法会使正常的PHP逻辑过载。同样地,(string)$element将为您提供元素的完整文本内容,但它在实际的XML中被分解。

因此,print_r输出不会为您提供对象的“真实”视图,因此应谨慎使用。有a couple of alternative debug functions I've written here可以更准确地了解对象的行为方式。