Handle Unwanted Character Changes In Json For Unicodes Encoding In PHP

Handle Unwanted Character Changes In Json For Unicodes Encoding In PHP

Json has been an efficient way to handle information and message exchanges in web programming. For example, I usually use PHP to connect MySQL and retrieve information, then display as Json. So a webpage can “AJAX” the displayed Json to create a dynamic view on itself. However, while the information involves unicode characters, PHP turn them into unreadable codes. After google, I found the following is the best way to solve the problem.

$string = '你好嗎';  
echo json_encode($string); //Output "u4f60u597du55ce"  
echo preg_replace("#u([0-9a-f]+)#ie", "iconv('UCS-2', 'UTF-8', pack('H4', '1'))", json_encode($string)); // Output "你好嗎"