2

I am trying to JSON_encode data from a MySQL database. The characters in the DB are as should.

For example, some of the data contains this: è

When I print out to the browser, this is what I get for all items that have special characters:

{"category":null}

Here is the very basic watered down version of the code I am using to test:

$sql = mysql_query("SELECT category FROM master_cat ORDER BY category ASC");
    while ($row = mysql_fetch_assoc($sql))
        $output[] = $row;

print(json_encode($output));

How can I get actual data to appear in browser when I am reading the JSON on the web page and not null?

user2428118
  • 7,935
  • 4
  • 45
  • 72
TheLettuceMaster
  • 15,594
  • 48
  • 153
  • 259
  • That is a very basic watered down version if you can get `$output[] = $row` and `json_encode($output)` resulting in `{"category":null}` – dbf Sep 12 '12 at 22:57

2 Answers2

4

You could use utf8_encode on the text fields, but can you check that the data is, indeed, there? Maybe output the data in HTML instead of JSON-encoding it? Because on my system UTF8 is either recognized, gives error, or some characters are truncated.

NULL smells of database data missing.

If the data is there, then:

mysql_query('SET NAMES utf8;');
$sql = mysql_query("SELECT category FROM master_cat ORDER BY category ASC");
while ($row = mysql_fetch_assoc($sql))
    $output[] = array_map('utf8_encode', $row);

print(json_encode($output));

You might want to specify explicitly the MIME type and charset too:

Header('Content-Type: application/json; charset=UTF-8');

see What is the correct JSON content type?

Community
  • 1
  • 1
LSerni
  • 55,617
  • 10
  • 65
  • 107
2

You should use JSON_UNESCAPED_UNICODE to encode multibyte Unicode characters literally (default is to escape as \uXXXX). Available since PHP 5.4.0. In this case:

echo json_encode($output, JSON_UNESCAPED_UNICODE);