2

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?

asked Sep 6, 2011 at 12:22

3 Answers 3

1

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);
?>
answered Sep 6, 2011 at 12:31
Sign up to request clarification or add additional context in comments.

Comments

0

Use iconv to convert between charsets.

iconv("UTF-8", "CP1252", $data)
answered Sep 6, 2011 at 12:35

Comments

0

Use utf-8 charset per connection to the database.

answered Sep 6, 2011 at 12:37

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.