PHP json_encode 함수가 UTF-8 문자열을 16 진수 엔티티로 변환하는 이유는 무엇입니까?
다양한 언어를 다루는 PHP 스크립트가 있습니다. 불행히도을 사용하려고 할 때마다 json_encode
모든 유니 코드 출력은 16 진수 엔터티로 변환됩니다. 이것이 예상되는 동작입니까? 출력을 UTF-8 문자로 변환하는 방법이 있습니까?
다음은 내가보고있는 예입니다.
입력
echo $text;
산출
База данни грешка.
입력
json_encode($text);
산출
"\u0411\u0430\u0437\u0430 \u0434\u0430\u043d\u043d\u0438 \u0433\u0440\u0435\u0448\u043a\u0430."
PHP / 5.4.0부터라는 옵션이 "JSON_UNESCAPED_UNICODE"
있습니다. 확인 해봐:
http://se2.php.net/json_encode
따라서 다음을 시도해야합니다.
json_encode( $text, JSON_UNESCAPED_UNICODE );
JSON_UNESCAPED_UNICODE는 PHP 버전 5.4 이상에서 사용 가능합니다.
다음 코드는 버전 5.3 용입니다.
업데이트
html_entity_decode
pack
+ 보다 조금 더 효율적mb_convert_encoding
입니다.(*SKIP)(*FAIL)
백 슬래시 자체와 지정된 문자를JSON_HEX_*
플래그 별로 건너 뜁니다 .
function raw_json_encode($input, $flags = 0) {
$fails = implode('|', array_filter(array(
'\\\\',
$flags & JSON_HEX_TAG ? 'u003[CE]' : '',
$flags & JSON_HEX_AMP ? 'u0026' : '',
$flags & JSON_HEX_APOS ? 'u0027' : '',
$flags & JSON_HEX_QUOT ? 'u0022' : '',
)));
$pattern = "/\\\\(?:(?:$fails)(*SKIP)(*FAIL)|u([0-9a-fA-F]{4}))/";
$callback = function ($m) {
return html_entity_decode("&#x$m[1];", ENT_QUOTES, 'UTF-8');
};
return preg_replace_callback($pattern, $callback, json_encode($input, $flags));
}
한 가지 해결책은 먼저 데이터를 인코딩 한 다음 동일한 파일에서 디코딩하는 것입니다.
$string =json_encode($input, JSON_UNESCAPED_UNICODE) ;
echo $decoded = html_entity_decode( $string );
문자셋과 이스케이프되지 않은 유니 코드를 설정하고 싶습니다
header('Content-Type: application/json;charset=utf-8');
json_encode($data,JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT);
다음은 다양한 PHP 버전에 대한 통합 솔루션입니다.
우리 회사에서는 다양한 PHP 버전의 다른 서버를 사용하고 있으므로 모든 솔루션이 작동해야했습니다.
$phpVersion = substr(phpversion(), 0, 3)*1;
if($phpVersion >= 5.4) {
$encodedValue = json_encode($value, JSON_UNESCAPED_UNICODE);
} else {
$encodedValue = preg_replace('/\\\\u([a-f0-9]{4})/e', "iconv('UCS-4LE','UTF-8',pack('V', hexdec('U$1')))", json_encode($value));
}
크레딧은 Marco Gasi & abu 로 가야합니다 . PHP> = 5.4에 대한 솔루션은 json_encode 문서에서 제공됩니다.
raw_json_encode () 함수는 위의 나에게 문제가 해결되지 않았다 (어떤 이유로, 콜백 함수 내 PHP 5.2.5 서버에 오류가 제기).
그러나이 다른 솔루션은 실제로 작동했습니다.
https://www.experts-exchange.com/questions/28628085/json-encode-fails-with-special-characters.html
Credits should go to Marco Gasi. I just call his function instead of calling json_encode():
function jsonRemoveUnicodeSequences( $json_struct )
{
return preg_replace( "/\\\\u([a-f0-9]{4})/e", "iconv('UCS-4LE','UTF-8',pack('V', hexdec('U$1')))", json_encode( $json_struct ) );
}
json_encode($text, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
Since you asked:
Is there any way to convert the output to UTF-8 characters?
Another solution is to use utf8_encode.
This will encode your string to UTF-8
.
e.g.
foreach ($rows as $key => $row) {
$rows[$key]["keyword"] = utf8_encode($row["keyword"]);
}
echo json_encode($rows);
Is this the expected behavior?
the json_encode()
only works with UTF-8 encoded data.
maybe you can get an answer to convert it here: cyrillic-characters-in-phps-json-encode
'IT' 카테고리의 다른 글
ngSrc 경로가 404로 해석되면 기본값으로 대체하는 방법이 있습니까? (0) | 2020.07.02 |
---|---|
C 및 C ++ 컴파일러가 강제로 적용되지 않을 때 함수 시그니처에서 배열 길이를 허용하는 이유는 무엇입니까? (0) | 2020.07.02 |
Google지도 마커 아이콘 이미지 크기 조정 (0) | 2020.07.02 |
문자열의 시작 부분에서 문자열을 제거 (0) | 2020.07.02 |
C ++ Vector가 Vector라고 불리는 이유는 무엇입니까? (0) | 2020.07.02 |