2
votes

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;
}
1
Can you try changing print_r($output); to print_r($output->ad->url); in your code, and see what the output is? - zinga
@zinga that shows only the main data text.. like cc.xdirectx.com/clicklink.php?qry=067a9027 - kannu
What version of PHP are you running? It returns the full object with attributes for me, tested on PHP 5.4 and 5.6. Full code I'm using: pastebin.com/6uVyE5Xt - zinga
Can you check this: pastebin.com/J3yGb3jQ This is how i am getting the response. - kannu

1 Answers

1
votes

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.