Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php missing attributes while parsing XML

I have this xml coming from a 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>

When I try to parse using simplexml_load_string or SimpleXMLElement I am getting this result.

[ads] => SimpleXMLElement Object ( [@attributes] => Array ( [numAds] => 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
                    )
               )

The important thing missing is url visibleurl attribute which I need. I tried looking online and wasted complete day in fixing this, but no answer. Can someone rectify the mistake I am doing?

PHP CODE:

$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;
}
like image 213
kannu Avatar asked Sep 19 '26 20:09

kannu


1 Answers

The loading of the XML works fine, but print_r is not able to print everything from an XML object. See this repository for a solution if you want to dump the XML code: simplexml_debug

You can access the attribute you want with

echo $output->ads->ad[0]->url->attributes();

Which works perfectly fine.

like image 181
Bas van Stein Avatar answered Sep 22 '26 10:09

Bas van Stein



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!