[PHP] json_encode 유니코드 한글 깨짐 문제 해결 > PHP

본문 바로가기

PHP

[PHP] [PHP] json_encode 유니코드 한글 깨짐 문제 해결

회원사진
하나를하더라도최선을
2020-02-22 14:09 5,263 0

본문



// 한글 깨짐이라는 표현보다는 유니코드 변환이라고 해아 할까요..

// PHP에서 Array형 데이터를 JSON 포맷으로 출력하고자 하는 경우 json_encode 함수를 호출함으로써 간단하게 데이터 변환이 가능하다.

// 단, 해당 함수는 UTF-8 형태의 String 값만을 사용할 수 있기 때문에 iconv를 사용하여 UTF-8 인코딩을 하여 사용해야만 한다.

// 그런데 여기서 문제가 발생하는데, 한글 데이터를 사용할 경우 json_encode 함수가 한글을 유니코드 형태로 자동으로 변환해서 출력하게끔 되어 있다.

{"code":0,"msg":"\uc694\uccad\ud558\uc2e0 \uc791\uc5c5\uc774 \ubaa8\ub450 \ucc98\ub9ac\ub418\uc5c8\uc2b5\ub2c8\ub2e4."}

// PHP 5.4 버전 이상을 사용할 경우, 다음과 같이 상수 변수 값을 옵션으로 줌으로써 간단하게 해결이 가능하다.

$json_Data = json_encode($arrJson, JSON_UNESCAPED_UNICODE);

// 그러나, 하위 버전 PHP를 사용하는 경우 json_encode 함수가 옵션 값을 받지 않기 때문에 해당 방법을 사용할 수 없다.

// 따라서, 다음의 함수를 추가하여 해결하도록 한다.

function han ($s) { return reset(json_decode('{"s":"'.$s.'"}')); }

function to_han ($str) { return preg_replace('/(\\\u[a-f0-9]+)+/e','han("$0")',$str); }

$json_Data = to_han(json_encode($arrJson));

function raw_json_encode($input) {

return preg_replace_callback(

'/\\\\u([0-9a-zA-Z]{4})/',

function ($matches) {

return mb_convert_encoding(pack('H*',$matches[1]),'UTF-8','UTF-16');

},

json_encode($input)

);

}

$json_Data = raw_json_encode($arrJson);




// 배열을 json_encode()해서 json으로 바꿀 때 한글 값이 유니코드로 깨져 들어가는 현상을 해결하는 방법
// PHP 버젼별로 다르게 구현
 
 
※ 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($arrfunction (&$item$key) { if (is_string($item)) $item = mb_encode_numericentity($itemarray (0x800xffff00xffff), 'UTF-8'); });
    return mb_decode_numericentity(json_encode($arr), array (0x800xffff00xffff), 'UTF-8');
}
 
$array = array("foo","bar");
$result = my_json_encode($array);
 
 
※ PHP 5.4 이상
 
$array = array("foo","bar");
$result = json_encode($array,JSON_UNESCAPED_UNICODE);

댓글목록0

등록된 댓글이 없습니다.
게시판 전체검색