JSON

PHP格式化json数据的实例

字号+ 作者:H5之家 来源:H5之家 2017-02-06 15:06 我要评论( )

三零网提供网络编程、 PHP编程 的技术文章PHP格式化json数据的实例给大家,希望大家喜欢,关键词PHP格式化json数据的实例

<?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 */ $arr = array("ret"=>0,"data"=>array('a' => 1, 'b' => "三零技术", 'c' => 3, 'd' => 4, 'e' => 5)); $json = json_encode($arr); 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 '{': $tabcount++; $result .= $char . $newline . str_repeat($tab, $tabcount); break; 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; } echo _format_json($json); /* { "ret": 0, "data": { "a": 1, "b": "\u811a\u672c\u4e4b\u5bb6", "c": 3, "d": 4, "e": 5 } } **/ ?>

 

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

相关文章
  • ABP入门系列(8)

    ABP入门系列(8)

    2017-02-03 12:01

  • JSON数据处理,一条龙服务

    JSON数据处理,一条龙服务

    2017-02-02 09:01

  • JSON数据中有null导致数据加载失败的解决办法

    JSON数据中有null导致数据加载失败的解决办法

    2017-02-01 12:04

  • jquery处理json数据返回数组和输出的方法

    jquery处理json数据返回数组和输出的方法

    2017-01-28 11:04

网友点评
=