出现一些问题后,我按如下方式修改了代码,但它不起作用:
$xml = simplexml_load_string($content) or die("Error: Cannot create object");
#var_dump($xml);
#exit;
if(!empty($xml)) {
foreach($xml->answer->result as $result) {
if (!empty($result)) {
foreach($result->attributes() as $a => $b) {
echo $a,'="',$b,"\"\n";
}
}
}
}
请注意,如果在第一个exit
循环之后我foreach
获得了预期的结果,则意味着空元素确实存在问题。这是要解析的xml:
<response>
<method>keyword.domain.seo</method>
<answer>
<result kw="moos im garten" position="47" competition="0" traffic="20" url="https://www.example.org"/>
<result kw="moos entfernen" position="75" competition="39" traffic="30" url="https://www.example.org"/>
</answer>
<date>2018-09-03T15:56:07+02:00</date>
<credits used="2"/>
</response>
关于我能做什么的任何想法?
答案 0 :(得分:0)
This should work
$content=<<<XML
<response>
<method>keyword.domain.seosssssss</method>
<answer>
<result kw="moos entfernen" position="74" competition="39" traffic="30" url="https://www.gartenbau.org/moos-entfernen-201816621"/>
<result kw="moosentfernundddddddddddddddg" position="93" competition="52" traffic="20" url="https://www.gartenbau.org/moos-entfernen-201816621"/>
</answer>
<date>2018-08-27T15:13:04+02:00</date>
<credits used="2"/>
</response>
XML;
$xml=simplexml_load_string($content) or die("Error: Cannot create object");
#var_dump($xml);
#exit;
if(!empty($xml))
{
foreach($xml->answer->result as $result)
{
if (!empty($result))
{
foreach($result->attributes() as $a => $b)
{
echo $a,'="',$b,"\"\n";
}
}
}
}
答案 1 :(得分:0)
这解决了我的问题,我敢肯定这不是最好的解决方案,但至少可以奏效:
$xml=simplexml_load_string($content) or die("Error: Cannot create object");
$results = $xml->answer->result;
if(!empty($results))
{
foreach($results as $result)
{
if (!empty($result))
{
foreach($result->attributes() as $a => $b)
{
echo $a,'="',$b,"\"\n";
}
}
}
}