我正在构建一个PHP脚本,将JSON数据提供给另一个脚本。我的脚本将数据构建到一个大型关联数组中,然后使用json_encode输出数据。下面是一个脚本示例:
$data = array('a' => 'apple', 'b' => 'banana', 'c' => 'catnip');
header('Content-type: text/javascript');
echo json_encode($data);
上面的代码产生如下输出:
{"a":"apple","b":"banana","c":"catnip"}
如果你有少量的数据,这是很好的,但我更喜欢这样的东西:
{
"a": "apple",
"b": "banana",
"c": "catnip"
}
有没有办法在PHP中做到这一点,而不需要丑陋的黑客?似乎Facebook的某个人发现了这一点。
我通常会用这些简单的语句。
如果你已经有一个JSON字符串,你可以简单地使用echo()和print_r()的组合。
不要忘记将print_r()的第二个参数传递给true,以便它返回值而不是打印它:
echo('<pre>' . print_r($json, true) . '</pre>');
或者你可以使用die(),这对调试很方便:
die('<pre>' . print_r($json, true) . '</pre>');
如果您有一个数组,您需要在之前将其转换为JSON字符串。
请确保使用JSON_PRETTY_PRINT标志设置json_encode()的第二个参数,这样您的JSON将被正确呈现:
echo('<pre>' . print_r(json_encode($array, JSON_PRETTY_PRINT), true) . '</pre>');
或者用于调试:
die('<pre>' . print_r(json_encode($array, JSON_PRETTY_PRINT), true) . '</pre>');
把几个答案粘在一起适合我对现有json的需求:
Code:
echo "<pre>";
echo json_encode(json_decode($json_response), JSON_PRETTY_PRINT);
echo "</pre>";
Output:
{
"data": {
"token_type": "bearer",
"expires_in": 3628799,
"scopes": "full_access",
"created_at": 1540504324
},
"errors": [],
"pagination": {},
"token_type": "bearer",
"expires_in": 3628799,
"scopes": "full_access",
"created_at": 1540504324
}