For some reason the item \"description\" returns NULL
with the following code:
You should pass utf8 encoded string in json_encode. You can use utf8_encode
and array_map()
function like below:
<?php
$encoded_rows = array_map('utf8_encode', $rows);
echo json_encode($encoded_rows);
?>
few day ago I have the SAME problem with 1 table.
Firstly try:
echo json_encode($rows);
echo json_last_error(); // returns 5 ?
If last line returns 5, problem is with your data. I know, your tables are in UTF-8, but not entered data. For example the input was in txt file, but created on Win machine with stupid encoding (in my case Win-1250 = CP1250) and this data has been entered into the DB.
Solution? Look for new data (excel, web page), edit source txt file via PSPad (or whatever else), change encoding to UTF-8, delete all rows and now put data from original. Save. Enter into DB.
You can also only change encoding to utf-8 and then change all rows manually (give cols with special chars - desc, ...). Good for slaves...
ntd's anwser didn't solve my problem. For those in same situation, here is how I finally handled this error: Just utf8_encode each of your results.
while($row = mysql_fetch_assoc($result)){
$rows[] = array_map('utf8_encode', $row);
}
Hope it helps!
If you have at least PHP 5.5, you can use json_last_error_msg(), which will return a string describing the problem.
If you don't have 5.5, but are on/above 5.3, you can use json_last_error() to see what the problem is.
It will return an integer, that you can use to identify the problem in the function's documentation. Currently (2012.01.19), the identifiers are:
0 = JSON_ERROR_NONE
1 = JSON_ERROR_DEPTH
2 = JSON_ERROR_STATE_MISMATCH
3 = JSON_ERROR_CTRL_CHAR
4 = JSON_ERROR_SYNTAX
5 = JSON_ERROR_UTF8
These can change in future versions, so it's better to consult the manual.
If you are below 5.3, you are out of luck, there is no way to ask what the error was.
The PHP.net recommended way of setting the charset is now this:
mysqli_set_charset('utf8')
I had the same problem and the solution was to use my own function instead of json_encode()
echo '["' . implode('","', $row) . '"]';