Search code examples
phpjsonparsingquoteapostrophe

JSON text unparseable when using cURL to grab it?


I have this really long JSON string: http://pastebin.com/2jJKSGHs , which is being pulled from a music API.

I have this code set up to parse it ( http://pastebin.com/EuJtuhHg ):

$url = "https://api.discogs.com/database/search?type=artist&q=pink[keyandsecretredacted]"; 

//initialize the session
$ch = curl_init();

//Set the User-Agent Identifier
curl_setopt($ch, CURLOPT_USERAGENT, 'YourSite/0.1 +http://your-site-here.com');

//Set the URL of the page or file to download.
curl_setopt($ch, CURLOPT_URL, $url);

//Ask cURL to return the contents in a variable instead of simply echoing them
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

//Execute the curl session
$output = curl_exec($ch);

//close the session
curl_close ($ch);


//decode and print output
$output = json_decode($output2, true);
echo($output['results'][0]['title']);

When I insert the contents of the JSON string directly into my code, the json_decode works perfectly on it. But when I try to grab it from the API using the method above, nothing prints on my page -- it's just empty. Printing out json_last_error returns "0", so it's not detecting any errors.

Any ideas why this might be happening?


Solution

  • Replace

    $output = curl_exec($ch);
    

    with

    $output2 = curl_exec($ch);
    

    Otherwise $output2 isn't defined, and json_decode is using an undefined variable:

    $output = json_decode($output2, true);