这是我的代码:
$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] 而不是整个数组?我不明白。
最佳答案
@Yottatron 的建议是正确的,但并非如本示例所示的所有情况:
如果您的 XML 是这样的:
<?xml version='1.0'?>
<testing>
<lol>
<lolelem>Lol1</lolelem>
<lolelem>Lol2</lolelem>
<notlol>NotLol1</lolelem>
<notlol>NotLol1</lolelem>
</lol>
</testing>
Simplexml 的输出将是:
SimpleXMLElement Object
(
[lol] => SimpleXMLElement Object
(
[lolelem] => Array
(
[0] => Lol1
[1] => Lol2
)
[notlol] => Array
(
[0] => NotLol1
[1] => NotLol1
)
)
)
并通过写作
$xml->lol->lolelem
你希望你的结果是
Array
(
[0] => Lol1
[1] => Lol2
)
但取而代之的是:
SimpleXMLElement Object
(
[0] => Lol1
)
和通过
$xml->lol->children()
你会得到:
SimpleXMLElement Object
(
[lolelem] => Array
(
[0] => Lol1
[1] => Lol2
)
[notlol] => Array
(
[0] => NotLol1
[1] => NotLol1
)
)
如果你只想要 lolelem 的,你需要做什么:
$xml->xpath("//lol/lolelem")
这给出了这个结果(不是预期的形状但包含正确的元素)
Array
(
[0] => SimpleXMLElement Object
(
[0] => Lol1
)
[1] => SimpleXMLElement Object
(
[0] => Lol2
)
)
关于php - 为什么 SimpleXML 在我使用它时将我的数组更改为数组的第一个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6796797/