PHP json中文

json_encode 和 json_decode 只支持utf-8编码的字符串,GBK的字符串要用json就得转换成utf-8字符串

看效果

<?php

header("Content-type:text/html; charset=utf-8");

$dirname = $_GET['dirname'];
$dirname = iconv('utf-8', 'GBK', $dirname);

$filename = array();

function read_all ($dir){
    global $filename; //使用全局变量

    if(!is_dir($dir)) return false;

    $handle = opendir($dir);
    if($handle){
        while(($fl = readdir($handle)) != false){
            $temp = $dir.DIRECTORY_SEPARATOR.$fl;
            if(is_dir($temp) && $fl!='.' && $fl != '..'){
                read_all($temp);
            }else{
                if($fl!='.' && $fl != '..'){
                    $temp = iconv('GBK', 'utf-8', $temp); //再将GBK编码转换为utf-8编码
                    $filename[] = $temp;
                }
            }
        }
    }
}

read_all($dirname);

echo json_encode($filename, JSON_UNESCAPED_UNICODE);

?>

不使用iconv转换编码效果
1
使用iconv转换编码效果
2
JSON_UNESCAPED_UNICODE
JSON_UNESCAPED_UNICODE是PHP5.4版本后新加的。加入以后,就不会对中文编码
加入前后的效果对比

echo json_encode($filename);
echo '<br>';
echo json_encode($filename, JSON_UNESCAPED_UNICODE);

1

posted @ 2018-08-26 09:15  thomas_blog  阅读(100)  评论(0编辑  收藏  举报