/**
* 将utf-8编码串转成原字符串
* @param string $str utf-8编码
* @return string 原字符串
*/
function unicode2utf8($str) {
if (! $str)
return $str;
$decode = json_decode ( $str [0] );
if ($decode)
return $decode;
$str = '["' . $str [0] . '"]';
$decode = json_decode ( $str );
if (count ( $decode ) == 1) {
return $decode [0];
}
return $str;
}
/**
* 将json串格式化成串输出,对于有缺损的json串同样可以进行格式化
* 例:
*
* {
* "枯asdf":{
* "adsf":[
* "hffe顶替标有"
* ],
* "0":"asdf"
* },
* "0":"hahakao"
* }
*
* @param string $json
* @return void
*/
function dumpjson($json) {
$isnojson = json_decode ( $json, true );
$json = preg_replace_callback ( "/(\uw{4})/", "unicode2utf8", $json );
$json = preg_replace ( "/\//", '/', $json );
$data = indent ( $json );
return "<pre>{$data}</pre>";
}
function indent($json) {
$result = '';
$pos = 0;
$strLen = mb_strlen ( $json, "utf-8" );
$indentStr = ' ';
$newLine = "n";
$prevChar = '';
$outOfQuotes = true;
for($i = 0; $i <= $strLen; $i ++) {
// Grab the next character in the string.
$char = mb_substr ( $json, $i, 1, "utf-8" );
// Are we inside a quoted string?
if ($char == '"' && $prevChar != '') {
$outOfQuotes = ! $outOfQuotes;
// If this character is the end of an element,
// output a new line and indent the next line.
} else if (($char == '}' || $char == ']') && $outOfQuotes) {
$result .= $newLine;
$pos --;
for($j = 0; $j < $pos; $j ++) {
$result .= $indentStr;
}
}
// Add the character to the result string.
$result .= $char;
// If the last character was the beginning of an element,
// output a new line and indent the next line.
if (($char == ',' || $char == '{' || $char == '[') && $outOfQuotes) {
$result .= $newLine;
if ($char == '{' || $char == '[') {
$pos ++;
}
for($j = 0; $j < $pos; $j ++) {
$result .= $indentStr;
}
}
$prevChar = $char;
}
$result = preg_replace ( '/\\/', '', $result );
$result = preg_replace ( '/\"/', '"', $result );
return $result;
}