-1

I am calling a Json Array from an API. My doubt is about the way I am getting all the data.

The API has a section to try out the response you should be getting from the API and when I do it I am getting data listed like here

as you can see there are 10 rows going from 0 to 9. But when I am calling the Json array, I am getting this here

as you can see it is all messy.

why is this happening ?? and how can I fix it ?.

I am calling data like this:

$curl = curl_init();
//adding fields to the curl object to enter the site
curl_setopt($curl, CURLOPT_URL, $my_url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);  
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate');

//executing the curl call and getting data back
$json = curl_exec($curl);

curl_close($curl); // close the connection
echo $json;

1 Answers1

0

The answer is: it's perception and not a bug per se.

Browsers can be very helpful when it comes to displaying data. When the browser receives a header with the appropriate content type for json (I believe it's application/json) it will try to parse the content as json. This is your first screenshot, when you see the data from the source, where it probably gets the correct headers.

I expect that your php script doesn't set any headers before the code sample you gave us, leaving php itself to decide, what headers to sent. Which means it will usually fallback to "text/html" (because that's what php is historically used for). Now, when your browser receives that header, it will try to parse your json as html, which won't work. Thus it prints it "messy".

Now, to be perfectly clear here: in the first screenshot the 0..9 in every row, this is just a view that your browser offers you, this is not explicitly in the data. the data just says "this is an array, there are these elements in the array". even though the order is significant, but there are no keys for arrays in json!

To "fix" your problem, you have to add the appropriate headers for your content, probably a

header("Content-Type: application/json"); 

before your code will suffice - at least if i'm not mistaken with the mime type here (but I assume What is the correct JSON content type? holds the right information).

Jakumi
  • 7,105
  • 2
  • 11
  • 28