简体   繁体   中英

Convert “Java source code characters” in JSON string using PHP

I have a JSON string that contains Dal\é . When I use json_decode on the JSON, it is converted to Dalé , however the original string that the JSON is from is Dalé . Why is this not converted properly?

I have found that "\é" is the C/C++/Java source code encoding for é . However, to me this doesn't answer why this is going wrong.


Example of incorrect PHP output:

<?php
$opts = array('http'=>array('ignore_errors' => true));
$context = stream_context_create($opts);
$jsonurl = "http://api.kivaws.org/v1/loans/552804.json";
$json = file_get_contents($jsonurl, false, $context);
$json_output = array(json_decode($json));
$json_error = $json_output[0]->error;
$json_message = $json_error->message;

foreach ($json_output[0]->{'loans'} as $loan) {
echo 'Name: '.$loan->{'name'};
}
?>

You need to tell the web browser what encoding you are giving it.

<?php
header('content-type: text/plain; charset=utf-8');
var_dump(json_decode($jsonStr));

if you are using php 5.4 you may use the function options of json_encode() like this :-

echo $b=json_encode('Dalé',JSON_UNESCAPED_UNICODE);
echo json_decode($b);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM