我正在构建一个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的某个人发现了这一点。
1 - json_encode($rows,JSON_PRETTY_PRINT);返回带有换行符的美化数据。这对于命令行输入很有帮助,但正如您所发现的那样,在浏览器中看起来不那么漂亮。浏览器将接受换行符作为源(因此,查看页面源确实会显示漂亮的JSON),但它们并不用于在浏览器中格式化输出。浏览器需要HTML。
2 -使用这个功能github
<?php
/**
* Formats a JSON string for pretty printing
*
* @param string $json The JSON to make pretty
* @param bool $html Insert nonbreaking spaces and <br />s for tabs and linebreaks
* @return string The prettified output
* @author Jay Roberts
*/
function _format_json($json, $html = false) {
$tabcount = 0;
$result = '';
$inquote = false;
$ignorenext = false;
if ($html) {
$tab = " ";
$newline = "<br/>";
} else {
$tab = "\t";
$newline = "\n";
}
for($i = 0; $i < strlen($json); $i++) {
$char = $json[$i];
if ($ignorenext) {
$result .= $char;
$ignorenext = false;
} else {
switch($char) {
case '[':
case '{':
$tabcount++;
$result .= $char . $newline . str_repeat($tab, $tabcount);
break;
case ']':
case '}':
$tabcount--;
$result = trim($result) . $newline . str_repeat($tab, $tabcount) . $char;
break;
case ',':
$result .= $char . $newline . str_repeat($tab, $tabcount);
break;
case '"':
$inquote = !$inquote;
$result .= $char;
break;
case '\\':
if ($inquote) $ignorenext = true;
$result .= $char;
break;
default:
$result .= $char;
}
}
}
return $result;
}
以下是对我有效的方法:
test.php的内容:
<html>
<body>
Testing JSON array output
<pre>
<?php
$data = array('a'=>'apple', 'b'=>'banana', 'c'=>'catnip');
// encode in json format
$data = json_encode($data);
// json as single line
echo "</br>Json as single line </br>";
echo $data;
// json as an array, formatted nicely
echo "</br>Json as multiline array </br>";
print_r(json_decode($data, true));
?>
</pre>
</body>
</html>
输出:
Testing JSON array output
Json as single line
{"a":"apple","b":"banana","c":"catnip"}
Json as multiline array
Array
(
[a] => apple
[b] => banana
[c] => catnip
)
还要注意html中“pre”标签的使用。
希望这能帮助到别人