0

我正在使用 CakePHP 输出一个包含多个 UTF-8 编码字符串的数组。我为输出设置了布局(这是一种 REST API 方法):

<?php.
  header("Pragma: no-cache");.
  header("Cache-Control: no-store, no-cache, max-age=0, must-revalidate");.
  header('Content-Type: application/json; charset=UTF-8');.
  header("X-JSON: ".$content_for_layout);.
  echo $content_for_layout;.
?>

这是我的看法:

<?php echo json_encode($items); ?> 

我获取数据的数据库表以 utf-8 编码。但是,当我输出数据时,如果其中一个元素具有 à、á 等特殊字符,则该字符串将在 JSON 数组中设置为 null。如何正确输出我的数据?

4

3 回答 3

2

看起来您的数据库连接未设置为 utf-8,这是最重要的部分。因此,添加'encoding' => 'utf8'到您的数据库配置中app/config/database.php,例如:

    'default' => array(
        'driver'   => 'mysql',
        'host'     => 'YOURHOST',
        'login'    => 'YOURLOGIN',
        'password' => 'YOURPASS',
        'database' => 'YOURDB',
        'encoding' => 'utf8'
    ),

如果您未在连接中设置编码,将使用“默认”编码。默认可能不是 utf8。

于 2012-09-19T16:24:31.640 回答
1

这很可能意味着您的数据以 UTF-8 编码,很可能是因为数据库连接未设置为 UTF-8,而您实际上是在 PHP 端以 latin1 格式接收数据。有关所有陷阱的概要,请参阅在 Web 应用程序中从前到后处理 Unicode 。

于 2012-09-19T16:18:18.193 回答
0
$items = json_encode( array_map( function($text){ return is_string($text) ? utf8_encode($text) : $text; }, $items) )
echo $items;
于 2012-09-19T16:12:44.087 回答