在使用PHP中的Simple XML解析XML字符串时,我得到了不一致的XML标记
$str = '<?xml version="1.0"?><toplevel><CompleteSuggestion><suggestion data="google"/></CompleteSuggestion><CompleteSuggestion><suggestion data="google maps"/></CompleteSuggestion><CompleteSuggestion><suggestion data="google translate"/></CompleteSuggestion><CompleteSuggestion><suggestion data="google docs"/></CompleteSuggestion><CompleteSuggestion><suggestion data="google drive"/></CompleteSuggestion><CompleteSuggestion><suggestion data="google classroom"/></CompleteSuggestion><CompleteSuggestion><suggestion data="google news"/></CompleteSuggestion><CompleteSuggestion><suggestion data="google earth"/></CompleteSuggestion><CompleteSuggestion><suggestion data="google flights"/></CompleteSuggestion><CompleteSuggestion><suggestion data="google calendar"/></CompleteSuggestion></toplevel>';
$xml = simplexml_load_string($str);
$data = json_decode(json_encode($xml),true);
echo "ARRAY: <pre>";
var_dump($data);
在上述情况下,我正在使用谷歌的自动完成功能,并在CompleteSuggestions标签内回复建议。看看php数组,我得到一个包含10个项目的CompleteSuggestion数组。前9个键的键为[0],而最后一个键的键为['suggestion']。这对我来说很奇怪。
有人知道为什么Simple XML会这样做吗?我是如何解决它,或解析它,因为我的foreach正在收到偏移错误。谢谢!
答案 0 :(得分:0)
这是一个奇怪的 - 我在5.6上得到了相同的行为(除了1之外,所有这些都得到数字数组)。
作为解决方法,我使用了array_pop:
<?php
$str = '<?xml version="1.0"?><toplevel><CompleteSuggestion><suggestion data="google"/></CompleteSuggestion><CompleteSuggestion><suggestion data="google maps"/></CompleteSuggestion><CompleteSuggestion><suggestion data="google translate"/></CompleteSuggestion><CompleteSuggestion><suggestion data="google docs"/></CompleteSuggestion><CompleteSuggestion><suggestion data="google drive"/></CompleteSuggestion><CompleteSuggestion><suggestion data="google classroom"/></CompleteSuggestion><CompleteSuggestion><suggestion data="google news"/></CompleteSuggestion><CompleteSuggestion><suggestion data="google earth"/></CompleteSuggestion><CompleteSuggestion><suggestion data="google flights"/></CompleteSuggestion><CompleteSuggestion><suggestion data="google calendar"/></CompleteSuggestion></toplevel>';
$xml = simplexml_load_string($str);
$data = json_decode(json_encode($xml),true);
foreach ($data['CompleteSuggestion'] as $suggestion){
$sug = array_pop($suggestion);
echo $sug['@attributes']['data'] . "<br />";
}
答案 1 :(得分:0)
这是非常有趣的行为。我想,它发生的原因是你的xml中有多个suggestion
标签,而SimpleXML试图将这个xml解析为一个名为suggestion
的字段的对象,然后当解析器遇到另一个具有相同名称的标签时该对象进入数组。
因此,我不会依赖内置的SimpleXML数据结构,并建议您按照Liam的建议预处理收到的数据。