모두와 나누는 웹개발 노트

share and care with love.

PHP & Laravel

[PHP] json_encode() 한글 깨지는 현상 해결 방법

mere hope 2016. 11. 14. 21:20

배열을 json_encode() 해서 json으로 바꿀때 한글 값이 유니코드로 깨져 들어가는 현상을 해결하는 방법.

PHP 버전별로 다르게 구현한다.



1. PHP 5.4 이상

$array = array("foo","bar");
$result = json_encode($array,JSON_UNESCAPED_UNICODE);


2. PHP 5.3 이하

function my_json_encode($arr)
{
    //convmap since 0x80 char codes so it takes all multibyte codes (above ASCII 127). So such characters are being "hidden" from normal json_encoding
    array_walk_recursive($arr, function (&$item, $key) { if (is_string($item)) $item = mb_encode_numericentity($item, array (0x80, 0xffff, 0, 0xffff), 'UTF-8'); });
    return mb_decode_numericentity(json_encode($arr), array (0x80, 0xffff, 0, 0xffff), 'UTF-8');
}
$array = array("foo","bar");
$result = my_json_encode($array);


출처: http://php.net/manual/kr/function.json-encode.php#105789

반응형
LIST