개발! 딱 깔끔하고 센스있게!

PHP 5.3에서 JSON을 이스케이프 처리되지 않은 UTF-8로 저장하는 방법은 무엇입니까? 본문

개발 스크랩 메모/PHP

PHP 5.3에서 JSON을 이스케이프 처리되지 않은 UTF-8로 저장하는 방법은 무엇입니까?

렉사이 2020. 12. 17. 22:36

json 파일을 만들었습니다:

$json = array( "Sample" =>array( "context" => $context, "date" => $date ) ); $url= "sample.json"; $myfile = fopen($url, "w") or die("Unable to open file!"); fwrite($myfile, json_encode($json)); fclose($myfile); 

나는 그것을 utf -8 으로 저장하고, 나는 php 5.3에서 json -unescaped -unicode 를 사용할 수 없다.

그럼 나 이제 어떡하지?

대답

json -unscaped -unicode 를 사용할 수 없다면 json 에 대한 인코딩을 할 수 있습니다:

$json = array( 'Sample' => array( 'context' => 'جمهوری اسلامی ایران' ) ); $encoded = json_encode($json); var_dump($encoded); // context: "\u062c\u0645..." $unescaped = preg_replace_callback('/\\\\u(\w{4})/', function ($matches) { return html_entity_decode('&#x' . $matches[1] . ';', ENT_COMPAT, 'UTF-8'); }, $encoded); var_dump($unescaped); // context is unescaped file_put_contents('sample.json', $unescaped); 

다음은 php5.3의 예입니다.

그러나 이것은 필수적인 것이 아니라, 어떤 json 해상장치도 정확하게 해석해야 할 유니코드 문자 문자를 다시 돌려야 하기 때문이다.

편집: 더 좋은 패턴은 / (?)

' u1234 >예를 보다.

Comments