这是我的代码:
$string = <<<XML <?xml version='1.0'?> <test> <testing> <lol>hello</lol> <lol>there</lol> </testing> </test> XML; $xml = simplexml_load_string($string); echo "All of the XML:\n"; print_r $xml; echo "\n\nJust the 'lol' array:"; print_r $xml->testing->lol;
输出:
All of the XML:
SimpleXMLElement Object
(
[testing] => SimpleXMLElement Object
(
[lol] => Array
(
[0] => hello
[1] => there
)
)
)
Just the 'lol' array:
SimpleXMLElement Object
(
[0] => hello
)
为什么它只输出[0]而不是整个数组?我不懂.
这是因为你有两个lol元素.要访问第二个,您需要这样做:
$xml->testing->lol[1];
这会给你“那里”
$xml->testing->lol[0];
会给你“你好”
SimpleXMLElement的children()方法将为您提供一个包含元素的所有子元素的对象,例如:
$xml->testing->children();
将为您提供一个包含“测试”SimpleXMLElement的所有子项的对象.
如果需要迭代,可以使用以下代码:
foreach($xml->testing->children() as $ele)
{
var_dump($ele);
}
这里有关于SimpleXMLElement的更多信息:
http://www.php.net/manual/en/class.simplexmlelement.php