php 的json_encode能把數(shù)組轉(zhuǎn)換為json格式的字符串。字符串沒有縮進(jìn),中文會轉(zhuǎn)為unicode編碼,例如\u975a\u4ed4。人閱讀比較困難?,F(xiàn)在這個方法在json_encode的基礎(chǔ)上再進(jìn)行一次美化處理。使人能方便閱讀內(nèi)容。
1. 使用 json_encode 輸出
<?php header('content-type:application/json;charset=utf8'); $arr = array( 'status' => true, 'errMsg' => '', 'member' =>array( array( 'name' => '李逍遙', 'gender' => '男' ), array( 'name' => '趙靈兒', 'gender' => '女' ) ) ); echo json_encode($arr); ?>
輸出:
{"status":true,"errMsg":"","member":[{"name":"\u674e\u900d\u9065","gender":"\u7537"},{"name":"\u8d75\u7075\u513f","gender":"\u5973"}]}
可以看出,這種格式人閱讀很困難。
2. 使用 jsonFormat 輸出
<?php /** Json數(shù)據(jù)格式化 * @param Mixed $data 數(shù)據(jù) * @param String $indent 縮進(jìn)字符,默認(rèn)4個空格 * @return JSON */ function jsonFormat($data, $indent=null){ // 對數(shù)組中每個元素遞歸進(jìn)行urlencode操作,保護(hù)中文字符 array_walk_recursive($data, 'jsonFormatProtect'); // json encode $data = json_encode($data); // 將urlencode的內(nèi)容進(jìn)行urldecode $data = urldecode($data); // 縮進(jìn)處理 $ret = ''; $pos = 0; $length = strlen($data); $indent = isset($indent)? $indent : ' '; $newline = "\n"; $prevchar = ''; $outofquotes = true; for($i=0; $i<=$length; $i++){ $char = substr($data, $i, 1); if($char=='"' && $prevchar!='\\'){ $outofquotes = !$outofquotes; }elseif(($char=='}' || $char==']') && $outofquotes){ $ret .= $newline; $pos --; for($j=0; $j<$pos; $j++){ $ret .= $indent; } } $ret .= $char; if(($char==',' || $char=='{' || $char=='[') && $outofquotes){ $ret .= $newline; if($char=='{' || $char=='['){ $pos ++; } for($j=0; $j<$pos; $j++){ $ret .= $indent; } } $prevchar = $char; } return $ret; } /** 將數(shù)組元素進(jìn)行urlencode * @param String $val */ function jsonFormatProtect(&$val){ if($val!==true && $val!==false && $val!==null){ $val = urlencode($val); } } header('content-type:application/json;charset=utf8'); $arr = array( 'status' => true, 'errMsg' => '', 'member' =>array( array( 'name' => '李逍遙', 'gender' => '男' ), array( 'name' => '趙靈兒', 'gender' => '女' ) ) ); echo jsonFormat($arr); ?>
輸出:
{ "status":true, "errMsg":"", "member":[ { "name":"李逍遙", "gender":"男" }, { "name":"趙靈兒", "gender":"女" } ] }
php5.4 以后,json_encode增加了JSON_UNESCAPED_UNICODE ,JSON_PRETTY_PRINT 等幾個常量參數(shù)。使顯示中文與格式化更方便。
header('content-type:application/json;charset=utf8'); $arr = array( 'status' => true, 'errMsg' => '', 'member' =>array( array( 'name' => '李逍遙', 'gender' => '男' ), array( 'name' => '趙靈兒', 'gender' => '女' ) ) ); echo json_encode($arr, JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT);
<br/>輸出:
{ "status": true, "errMsg": "", "member": [ { "name": "李逍遙", "gender": "男" }, { "name": "趙靈兒", "gender": "女" } ] }
<br/>JSON常量參數(shù)說明:
以下常量表示了 json_last_error() 所返回的錯誤類型。
JSON_ERROR_NONE (integer) 沒有錯誤發(fā)生。自 PHP 5.3.0 起生效。 JSON_ERROR_DEPTH (integer) 到達(dá)了最大堆棧深度。自 PHP 5.3.0 起生效。 JSON_ERROR_STATE_MISMATCH (integer) 出現(xiàn)了下溢(underflow)或者模式不匹配。自 PHP 5.3.0 起生效。 JSON_ERROR_CTRL_CHAR (integer) 控制字符錯誤,可能是編碼不對。自 PHP 5.3.0 起生效。 JSON_ERROR_SYNTAX (integer) 語法錯誤。 自 PHP 5.3.0 起生效。 JSON_ERROR_UTF8 (integer) 異常的 UTF-8 字符,也許是因?yàn)椴徽_的編碼。 此常量自 PHP 5.3.1 起生效。
<br/>下面的常量可以和 json_encode() 的 form 選項(xiàng)結(jié)合使用。
JSON_HEX_TAG (integer) 所有的 < 和 > 轉(zhuǎn)換成 \u003C 和 \u003E。 自 PHP 5.3.0 起生效。 JSON_HEX_AMP (integer) 所有的 & 轉(zhuǎn)換成 \u0026。 自 PHP 5.3.0 起生效。 JSON_HEX_APOS (integer) 所有的 ' 轉(zhuǎn)換成 \u0027。 自 PHP 5.3.0 起生效。 JSON_HEX_QUOT (integer) 所有的 " 轉(zhuǎn)換成 \u0022。 自 PHP 5.3.0 起生效。 JSON_FORCE_OBJECT (integer) 使一個非關(guān)聯(lián)數(shù)組輸出一個類(Object)而非數(shù)組。 在數(shù)組為空而接受者需要一個類(Object)的時(shí)候尤其有用。 自 PHP 5.3.0 起生效。 JSON_NUMERIC_CHECK (integer) 將所有數(shù)字字符串編碼成數(shù)字(numbers)。 自 PHP 5.3.3 起生效。 JSON_BIGINT_AS_STRING (integer) 將大數(shù)字編碼成原始字符原來的值。 自 PHP 5.4.0 起生效。 JSON_PRETTY_PRINT (integer) 用空白字符格式化返回的數(shù)據(jù)。 自 PHP 5.4.0 起生效。 JSON_UNESCAPED_SLASHES (integer) 不要編碼 /。 自 PHP 5.4.0 起生效。 JSON_UNESCAPED_UNICODE (integer) 以字面編碼多字節(jié) Unicode 字符(默認(rèn)是編碼成 \uXXXX)。 自 PHP 5.4.0 起生效。
本文講解了php JSON數(shù)據(jù)格式化的方法,更多相關(guān)內(nèi)容請關(guān)注php中文網(wǎng)。
相關(guān)推薦:
關(guān)于php session 讀寫鎖的相關(guān)內(nèi)容<br/>
利用php 來求水仙花數(shù)的優(yōu)化<br/>
如何通過php來驗(yàn)證身份證號碼<br/>
<br/>
The above is the detailed content of About php JSON data formatting method. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The method to get the current session ID in PHP is to use the session_id() function, but you must call session_start() to successfully obtain it. 1. Call session_start() to start the session; 2. Use session_id() to read the session ID and output a string similar to abc123def456ghi789; 3. If the return is empty, check whether session_start() is missing, whether the user accesses for the first time, or whether the session is destroyed; 4. The session ID can be used for logging, security verification and cross-request communication, but security needs to be paid attention to. Make sure that the session is correctly enabled and the ID can be obtained successfully.

To extract substrings from PHP strings, you can use the substr() function, which is syntax substr(string$string,int$start,?int$length=null), and if the length is not specified, it will be intercepted to the end; when processing multi-byte characters such as Chinese, you should use the mb_substr() function to avoid garbled code; if you need to intercept the string according to a specific separator, you can use exploit() or combine strpos() and substr() to implement it, such as extracting file name extensions or domain names.

UnittestinginPHPinvolvesverifyingindividualcodeunitslikefunctionsormethodstocatchbugsearlyandensurereliablerefactoring.1)SetupPHPUnitviaComposer,createatestdirectory,andconfigureautoloadandphpunit.xml.2)Writetestcasesfollowingthearrange-act-assertpat

In PHP, the most common method is to split the string into an array using the exploit() function. This function divides the string into multiple parts through the specified delimiter and returns an array. The syntax is exploit(separator, string, limit), where separator is the separator, string is the original string, and limit is an optional parameter to control the maximum number of segments. For example $str="apple,banana,orange";$arr=explode(",",$str); The result is ["apple","bana

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

std::chrono is used in C to process time, including obtaining the current time, measuring execution time, operation time point and duration, and formatting analysis time. 1. Use std::chrono::system_clock::now() to obtain the current time, which can be converted into a readable string, but the system clock may not be monotonous; 2. Use std::chrono::steady_clock to measure the execution time to ensure monotony, and convert it into milliseconds, seconds and other units through duration_cast; 3. Time point (time_point) and duration (duration) can be interoperable, but attention should be paid to unit compatibility and clock epoch (epoch)

ToaccessenvironmentvariablesinPHP,usegetenv()orthe$_ENVsuperglobal.1.getenv('VAR_NAME')retrievesaspecificvariable.2.$_ENV['VAR_NAME']accessesvariablesifvariables_orderinphp.iniincludes"E".SetvariablesviaCLIwithVAR=valuephpscript.php,inApach

In PHP, to pass a session variable to another page, the key is to start the session correctly and use the same $_SESSION key name. 1. Before using session variables for each page, it must be called session_start() and placed in the front of the script; 2. Set session variables such as $_SESSION['username']='JohnDoe' on the first page; 3. After calling session_start() on another page, access the variables through the same key name; 4. Make sure that session_start() is called on each page, avoid outputting content in advance, and check that the session storage path on the server is writable; 5. Use ses
