-1

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

Albert Prats
  • 786
  • 4
  • 15
  • 32
  • I don't see what would be wrong with that JSON output? – Bergi Jun 04 '14 at 09:38
  • your `JSON` is encoded correctly because special characters need to be encoded in the `JSON` string. if you do the output with the `jQuery` `html()` function, the special characters will be encoded to their html-equivalents correctly. for example: `$("#container").html(json_string);` – low_rents Jun 04 '14 at 09:40
  • You should use `echo htmlspecialchars(print_r($row, true));` btw – Bergi Jun 04 '14 at 09:50
  • Fine, I printed the results as html content and it shows the accented characters fine. Thanks all – Albert Prats Jun 04 '14 at 10:06

2 Answers2

2

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.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
2

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);
xdazz
  • 158,678
  • 38
  • 247
  • 274