php在解析XML时缺少属性

时间:2015-10-30 08:36:05

标签: php xml xml-parsing

我有这个xml来自API。

    <response>
<ads numAds="2">
<ad ranking="1">
<title>Artist News on Facebook®</title>
<description>
What&#39;s the most current music news? Sign up For Free to Find out!
</description>
<pixel_url>
http://cc.xdirectx.com/pixellink.php?qry=e8b6b726c
</pixel_url>
<url visibleurl="Facebook.com">
http://cc.xdirectx.com/clicklink.php?qry=067a9027
</url>
</ad>
<ad ranking="2">
<title>Artist News on Facebook®</title>
<description>
What&#39;s the most current music news? Sign up For Free to Find out!
</description>
<pixel_url>
http://cc.xdirectx.com/pixellink.php?qry=e8b6b726c
</pixel_url>
<url visibleurl="Facebook.com">
http://cc.xdirectx.com/clicklink.php?qry=067a9027
</url>
</ad>
</ads></response>

当我尝试使用 simplexml_load_string SimpleXMLElement 进行解析时,我得到了这个结果。

[ads] =&gt; SimpleXMLElement对象         (             [@attributes] =&gt;排列                 (                     [numAds] =&gt; 6                 )

        [ad] => Array
            (
                [0] => SimpleXMLElement Object
                    (
                        [@attributes] => Array
                            (
                                [ranking] => 1
                            )

                        [title] => Artist News on Facebook®
                        [description] => What's the most current music news? Sign up For Free to Find out!
                        [pixel_url] => http://cc.xdirectx.com/pixellink.php?qry=e8b6b726c
                        [url] => http://cc.xdirectx.com/clicklink.php?qry=067a9027
                    )
               )

缺少的重要事项是我需要的url visibleurl属性。 我尝试在线查看并浪费了整整一天来解决这个问题,但没有答案。 有人可以纠正我正在做的错误吗?

PHP代码:

$result = getCurlJson($urlParse);
$output = simplexml_load_string($result) or die("Error: Cannot create object");
echo '<pre>';
print_r($output);
echo '</pre>';

function getCurlJson($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL, $url);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

1 个答案:

答案 0 :(得分:1)

加载XML工作正常,但print_r无法打印XML object中的所有内容。如果要转储XML代码,请参阅此存储库以获取解决方案:simplexml_debug

您可以使用

访问所需的属性
echo $output->ads->ad[0]->url->attributes();

哪种效果很好。