PHP自定義函數(shù)格式化json數(shù)據(jù)示例
本文實例講述了PHP自定義函數(shù)格式化json數(shù)據(jù)的方法。分享給大家供大家參考,具體如下:
<?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 } } **/ ?>
PS:這里再為大家推薦幾款比較實用的json在線工具供大家參考使用:
在線JSON代碼檢驗、檢驗、美化、格式化工具:
http://tools.jb51.net/code/json
JSON在線格式化工具:
http://tools.jb51.net/code/jsonformat
在線XML/JSON互相轉(zhuǎn)換工具:
http://tools.jb51.net/code/xmljson
json代碼在線格式化/美化/壓縮/編輯/轉(zhuǎn)換工具:
http://tools.jb51.net/code/jsoncodeformat
C語言風(fēng)格/HTML/CSS/json代碼格式化美化工具:
http://tools.jb51.net/code/ccode_html_css_json
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《PHP中json格式數(shù)據(jù)操作技巧匯總》、《PHP針對XML文件操作技巧總結(jié)》、《PHP基本語法入門教程》、《PHP數(shù)組(Array)操作技巧大全》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家PHP程序設(shè)計有所幫助。
- javascript自定義日期比較函數(shù)用法示例
- JS中創(chuàng)建自定義類型的常用模式總結(jié)【工廠模式,構(gòu)造函數(shù)模式,原型模式,動態(tài)原型模式等】
- AngularJs1.x自定義指令獨立作用域的函數(shù)傳入?yún)?shù)方法
- JS自定義函數(shù)實現(xiàn)時間戳轉(zhuǎn)換成date的方法示例
- JavaWeb開發(fā)之JSTL標(biāo)簽庫的使用、 自定義EL函數(shù)、自定義標(biāo)簽(帶屬性的、帶標(biāo)簽體的)
- js document.getElementsByClassName的使用介紹與自定義函數(shù)
- 自定義require函數(shù)讓瀏覽器按需加載Js文件
- 常用原生js自定義函數(shù)總結(jié)
- JS自定義函數(shù)對web前端上傳的文件進行類型大小判斷
- 詳解JavaScript自定義函數(shù)
相關(guān)文章
基于yaf框架和uploadify插件,做的一個導(dǎo)入excel文件,查看并保存數(shù)據(jù)的功能
本文主要介紹了基于yaf框架和uploadify插件,做的一個導(dǎo)入excel文件,查看并保存數(shù)據(jù)的功能的思路與方法。具有很好的參考價值,下面跟著小編一起來看下吧2017-01-01PHP+HTML+JavaScript+Css實現(xiàn)簡單爬蟲開發(fā)
這篇文章主要為大家詳細介紹了PHP+HTML+JavaScript+Css實現(xiàn)簡單爬蟲開發(fā),具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-03-03