Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: JSON format outputs into one long single line

Tags:

json

php

here is my PHP script.

do2:locu alexus$ cat venuesearch.php 
<?php

$KEY='XXXXXXXXXXXXXXX';
$URL='http://api.locu.com/v1_0/venue/search/?api_key=';

$ch=curl_init();
curl_setopt($ch, CURLOPT_URL, $URL.$KEY);
curl_setopt($ch, CURLOPT_HEADER,0);

print_r(json_decode(curl_exec($ch),TRUE));

?>
do2:locu alexus$ 

locu service provides output in JSON format. When I run script I'm getting output all in long single line.

sample of output:

do2:locu alexus$ php venuesearch.php 
{"meta": {"cache-expiry": 3600, "limit": 25}, "objects": [{"categories": ["restaurant"], "country": "United States",.......... 

What am I missing? How can I access each of those variables? maybe it makes sense to convert it into XML?

* UPDATE * : .. in example #1 of PHP: json_decode - Manual shows formated output, if I use true then I get array, I'm not getting neither formatet output nor array.

like image 267
alexus Avatar asked Dec 03 '25 18:12

alexus


2 Answers

Try adding:

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

before execution.

It looks like the execution is simply printing the response rather than returning it as a string to be processed by json_decode.

like image 147
Stegrex Avatar answered Dec 06 '25 06:12

Stegrex


You should look at the original data:

$json = curl_exec($ch);
var_dump($json);

Your described output is only possible if the API returns a json encoded json string, like that:

"{\"meta\": {\"cache-expiry\": 3600, \"limit\": 25}, \"objects\": [{\"categories\": [\"restaurant\"], \"country\": \"United States\",.......... '

(note the outer quotes, they are part of the string)

This is very weird and definitly a bug in the API but the only way to get around it is to decode it twice:

$data = json_decode(json_decode($json));

Edit: Forget that, Stegrex has figured it out.

like image 37
Fabian Schmengler Avatar answered Dec 06 '25 06:12

Fabian Schmengler