简体   繁体   English

PHP:JSON格式输出成一行很长的一行

[英]PHP: JSON format outputs into one long single line

here is my PHP script. 这是我的PHP脚本。

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. locu服务提供JSON格式的输出。 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? 也许将其转换为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. * UPDATE * :..在PHP的示例1中:json_decode-手册显示了格式化的输出,如果我使用true则得到数组,但既没有得到格式化输出也没有得到数组。

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. 看起来执行只是在打印响应,而不是将其作为由json_decode处理的字符串返回。

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: 仅当API返回json编码的json字符串时,您才能描述输出,如下所示:

"{\"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: 这是很奇怪的,而且绝对是API中的错误,但是解决该错误的唯一方法是将其解码两次:

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

Edit: Forget that, Stegrex has figured it out . 编辑:忘记了, Stegrex已经弄清楚了

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM