我有一个简单的XML输出:
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"answers"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时没有看到它。
使用语法$element['attribute_name']
访问属性,因此在您的情况下,需要$row['name']
。
重要的是要记住,SimpleXML对象有点神奇——$element->child
、$element_list[0]
和$element['foo']
语法重载了正常的PHP逻辑。类似地,(string)$element
将为您提供元素的完整文本内容,但它在实际的XML中是分解的。
因此,print_r
输出不会为您提供对象的"真实"视图,因此应小心使用。我在这里写了几个可供选择的调试函数,它们可以更准确地了解对象的行为。