开发者

Array to json with json_encode and back to text

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 开发者_StackOverflownon 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ür 599,95€.

Any ideas?


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);

?>


Use iconv to convert between charsets.

iconv("UTF-8", "CP1252", $data)


Use utf-8 charset per connection to the database.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜