I retrieve data from a mysql database. I want to make this data available as json:
<?php
$data = array();
foreach($this->dataFromDb as $value){
$data[] = $value;
}
$json = json_encode($data);
echo $json;
?>
Unfortunately this produces null values in the json because e.g. $value['title'] may contain non utf-8 chars like €. To solve this I change this line.
$data[] = array_map(utf8_encode, $value);
But now I have strings like \u00 or \u0080 in the json output. How would I get my normal text like it is stored in db from the json? When I try
print_r(json_decode($json));
I again get strange chars like fÃ1⁄4r 599,95€.
Any ideas?
3 Answers 3
You also have to utf8_decode() the data:
<?php
$data = array();
$arr[] = 'a';
$arr[] = "\x80";
print_r($arr);
$data[] = array_map(utf8_encode, $arr);
$json = json_encode($data);
$decoded_json = json_decode($json);
print_r($decoded_json);
$decoded_data[] = array_map(utf8_decode, $decoded_json[0] );
print_r($decoded_data);
?>
Comments
Use iconv to convert between charsets.
iconv("UTF-8", "CP1252", $data)
Comments
Use utf-8 charset per connection to the database.