简体   繁体   中英

character encoding php - javascript

I got a php file that manages a entity in my database. 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.

The problem is that when the php script retrieves the values the accented chararters are displayed fine.

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:

["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:

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 ?

thanks

You're looking for the JSON_UNESCAPED_UNICODE flag for json_encode :

JSON_UNESCAPED_UNICODE ( integer )
Encode multibyte Unicode characters literally (default is to escape as \\uXXXX). Available since PHP 5.4.0.

There's nothing to do with the $stack input array. Btw, those escape values are valid JSON, there's no need to avoid them. They would even make your life easier in case you don't send your HTML with an Unicode encoding.

There is nothing wrong with your JSON result.

After PHP 5.4 , you could use the option of JSON_UNESCAPED_UNICODE , if you want.

echo json_encode($stack, JSON_UNESCAPED_UNICODE);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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