2011-09-06 61 views
2

我从mysql数据库检索数据。我想提供的JSON这样的数据:数组到json与json_encode并返回到文本

<?php 
    $data = array(); 

    foreach($this->dataFromDb as $value){ 
     $data[] = $value; 
    } 

    $json = json_encode($data); 

    echo $json; 
?> 

不幸的是这将产生在JSON null值,因为如$value['title']可能包含非UTF-8字符,如€。为了解决这个问题我改变了这一行。

$data[] = array_map(utf8_encode, $value); 

但现在我有这样的JSON输出\u00\u0080字符串。我如何得到我的普通文本,就像它存储在json的数据库中一样?当我尝试

print_r(json_decode($json)); 

我再次得到奇怪的字符,如für 599,95€

任何想法?

回答

1

您也可以utf8_decode()数据:

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

?> 
0

使用的iconv到字符集之间的转换。

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

每个连接使用utf-8字符集到数据库。