简体   繁体   English

字符编码php-JavaScript

[英]character encoding php - javascript

I got a php file that manages a entity in my database. 我有一个php文件,用于管理数据库中的实体。 What I want to do is to retrieve a set of strings from the database and return it via json_encode to a javascript function. 我想做的是从数据库中检索一组字符串,然后通过json_encode将其返回给javascript函数。

The problem is that when the php script retrieves the values the accented chararters are displayed fine. 问题是,当php脚本检索值时,重音字符显示良好。

When I output it like this: 当我这样输出时:

echo "<pre>";
print_r($row);
echo "</pre>";

I get: 我得到:

Array
(
    [0] => 1
    [1] => Que és la bolsa de trabajo de la FIB?
)

But when I want to return the data to the ajax call via json_encode I get this: 但是当我想通过json_encode将数据返回给ajax调用时,我得到了:

["1","Que \u00e9s la bolsa de trabajo de la FIB?"]

What I am doint to de data beore output it in the json_encode is: 我不是很想在json_encode中将其输出的数据是:

function encode_items(&$item, $key)
{
    $item = utf8_encode($item);
}

array_walk_recursive($stack, 'encode_items');
echo json_encode($stack);

Any idea on how to codify it correctly ?? 关于如何正确地编纂它的任何想法? I asume that if is shows properly in my echo in PHP it will show fine in my javascript ajax call, am I right ? 我认为,如果在PHP的回显中正确显示了它,则在我的javascript ajax调用中可以正常显示,对吗?

thanks 谢谢

You're looking for the JSON_UNESCAPED_UNICODE flag for json_encode : 您正在寻找json_encodeJSON_UNESCAPED_UNICODE 标志

JSON_UNESCAPED_UNICODE ( integer ) JSON_UNESCAPED_UNICODE整数
Encode multibyte Unicode characters literally (default is to escape as \\uXXXX). 按字面意义编码多字节Unicode字符(默认为转义为\\ uXXXX)。 Available since PHP 5.4.0. 自PHP 5.4.0起可用。

There's nothing to do with the $stack input array. $stack输入数组无关。 Btw, those escape values are valid JSON, there's no need to avoid them. 顺便说一句,这些转义值是有效的JSON,无需避免使用它们。 They would even make your life easier in case you don't send your HTML with an Unicode encoding. 如果您不使用Unicode编码发送HTML,它们甚至可以使您的生活更轻松。

There is nothing wrong with your JSON result. 您的JSON结果没有任何问题。

After PHP 5.4 , you could use the option of JSON_UNESCAPED_UNICODE , if you want. PHP 5.4之后,如果需要,可以使用JSON_UNESCAPED_UNICODE选项。

echo json_encode($stack, JSON_UNESCAPED_UNICODE);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM