1
votes

I'm creating a website that uses the etsy api to display shop info. I'm trying to access the individual values of the retruned json string. To do this I need to turn the returned string into an object. The only way I can see to do this is json_decode($response_body);, but I can't seem to get this to work. When I use the function it returns undefined/NULL when I try to get it's type. The returned string looks about like this: {"count":3,"results":[{"listing_id":252525252,"state":"active","user_id":1111111,"category_id":1234567,"title":"Title of product","description":"This is a description"}. Is there something I am doing completely wrong? Here is the code i'm using:

$url = "https://api.etsy.com/v2/shops/shopname/listings/active?api_key=".$apikey;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response_body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (intval($status) != 200) throw new Exception("HTTP $status\n$response_body");
$reponse_fixed = json_decode($response_body);
echo $response_fixed;
1
Is that the whole JSON string, or just a fragment? Because as a fragment, it is not valid JSON - at the least, it is missing a closing ] - Michael Berkowski
Post the output from var_dump($response_body) (copied from the page source so that whitespace is preserved) - Michael Berkowski
@MichaelBerkowski yea I'm sorry that's not valid. I just tried to type it out by hand. The Json that is returned seems to be valid, though - McMatt
If it is valid (can be validated with something like jsonlint.com) then json_decode() should work. Post it please, and we can take a look. You can check the output from json_last_error_msg() - Michael Berkowski
@MichaelBerkowski when I try echo var_dump($response_body) it does nothing. I'm assuming it's just returning undefined - McMatt

1 Answers

0
votes

json_decode returning null can be possible if the data that has been passed as an argument is an invalid JSON or empty. So make sure the response is in correct JSON format