[英]json_encode() excluding UTF-8 encoded string from output
I'm using CakePHP to output an array that contains several UTF-8 encoded strings. 我正在使用CakePHP输出包含几个UTF-8编码字符串的数组。 I have a layout set up for the output (it's a REST API method):
我为输出设置了布局(这是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;.
?>
This is my view: 这是我的看法:
<?php echo json_encode($items); ?>
My database table where I get the data is encoded in utf-8. 我获取数据的数据库表是用utf-8编码的。 But when I output the data if one of its elements has special characters like à, á, etc, the string will be set to null in the JSON array.
但是当我输出数据时,如果其元素之一具有特殊字符(如à,á等),则该字符串将在JSON数组中设置为null。 How can I properly output my data?
如何正确输出数据?
It looks like your database connection is not set to utf-8, which is the most important part. 看起来您的数据库连接未设置为utf-8,这是最重要的部分。 So add
'encoding' => 'utf8'
to the database configuration in your app/config/database.php
, for example: 因此,在您的
app/config/database.php
,将'encoding' => 'utf8'
到数据库配置中,例如:
'default' => array(
'driver' => 'mysql',
'host' => 'YOURHOST',
'login' => 'YOURLOGIN',
'password' => 'YOURPASS',
'database' => 'YOURDB',
'encoding' => 'utf8'
),
If you don't set the encoding in the connection, a "default" encoding will be used. 如果您未在连接中设置编码,则将使用“默认”编码。 The default is likely not utf8.
默认值可能不是utf8。
That most likely means your data is not encoded in UTF-8, most likely because the database connection is not set to UTF-8 and you're actually receiving the data in latin1 on the PHP side. 这最有可能意味着您的数据未使用UTF-8编码,最有可能是因为数据库连接未设置为UTF-8,并且实际上是在PHP端以latin1接收数据。 See Handling Unicode Front To Back In A Web App for a rundown of all gotchas.
有关所有陷阱的详细信息,请参见在Web应用程序中处理Unicode从头到尾。
$items = json_encode( array_map( function($text){ return is_string($text) ? utf8_encode($text) : $text; }, $items) )
echo $items;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.