我正在构建一个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的需求:
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
}
简单的方法为php>5.4:像在Facebook的图表
$Data = array('a' => 'apple', 'b' => 'banana', 'c' => 'catnip');
$json= json_encode($Data, JSON_PRETTY_PRINT);
header('Content-Type: application/json');
print_r($json);
浏览器中的结果
{
"a": "apple",
"b": "banana",
"c": "catnip"
}
你可以这样做。
$array = array(
"a" => "apple",
"b" => "banana",
"c" => "catnip"
);
foreach ($array as $a_key => $a_val) {
$json .= "\"{$a_key}\" : \"{$a_val}\",\n";
}
header('Content-Type: application/json');
echo "{\n" .rtrim($json, ",\n") . "\n}";
上面的输出有点像Facebook。
{
"a" : "apple",
"b" : "banana",
"c" : "catnip"
}
这个函数将接受JSON字符串并缩进,使其非常可读。它也是收敛的,
prettyPrint( $json ) === prettyPrint( prettyPrint( $json ) )
输入
{"key1":[1,2,3],"key2":"value"}
输出
{
"key1": [
1,
2,
3
],
"key2": "value"
}
Code
function prettyPrint( $json )
{
$result = '';
$level = 0;
$in_quotes = false;
$in_escape = false;
$ends_line_level = NULL;
$json_length = strlen( $json );
for( $i = 0; $i < $json_length; $i++ ) {
$char = $json[$i];
$new_line_level = NULL;
$post = "";
if( $ends_line_level !== NULL ) {
$new_line_level = $ends_line_level;
$ends_line_level = NULL;
}
if ( $in_escape ) {
$in_escape = false;
} else if( $char === '"' ) {
$in_quotes = !$in_quotes;
} else if( ! $in_quotes ) {
switch( $char ) {
case '}': case ']':
$level--;
$ends_line_level = NULL;
$new_line_level = $level;
break;
case '{': case '[':
$level++;
case ',':
$ends_line_level = $level;
break;
case ':':
$post = " ";
break;
case " ": case "\t": case "\n": case "\r":
$char = "";
$ends_line_level = $new_line_level;
$new_line_level = NULL;
break;
}
} else if ( $char === '\\' ) {
$in_escape = true;
}
if( $new_line_level !== NULL ) {
$result .= "\n".str_repeat( "\t", $new_line_level );
}
$result .= $char.$post;
}
return $result;
}