Reputation: 15734
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
?
Upvotes: 2
Views: 4563
Reputation: 21
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);
Upvotes: 2
Reputation: 57408
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?
Upvotes: 4