0

I have a function that return a list of cities (and some other data)

//after some logic
print_r($cities);
echo json_encode($cities);

Result of print_r after retreving one city, in this case Medellín city:

Array ( [0] => Array ( [id] => 1 [state_id] => 2 [name] => Medellín [propauthor] => 0 ) )

But the json_encode() just returns false

EDIT: json_last_error () returns JSON_ERROR_UTF8, as you can see cities might have tildes (accents)

JuanBonnett
  • 776
  • 3
  • 8
  • 26
  • What does json_last_error() return ? – NaeiKinDus Feb 24 '15 at 13:38
  • Hello, I updated my question to be more straightforward and avoid using non-necesary stuff... I'm gonna checkout that function you said – JuanBonnett Feb 24 '15 at 13:39
  • JSON_ERROR_UTF8 ... Some cities have accents, like in this case "Medellín, Colombia" my web application is ready with a UTF-8 Header, how can I fix this in this specific php file, it's called Via Ajax? – JuanBonnett Feb 24 '15 at 13:44
  • 4
    [json_encode produce JSON_ERROR_UTF8 from MSSQL-SELECT](http://stackoverflow.com/questions/18247737/json-encode-produce-json-error-utf8-from-mssql-select) ***OR*** [How to solve JSON_ERROR_UTF8 error in php json_decode?](http://stackoverflow.com/questions/10199017/how-to-solve-json-error-utf8-error-in-php-json-decode) ***OR*** [Why is this PHP call to json_encode silently failing - inability to handle single quotes?](http://stackoverflow.com/questions/9098507/why-is-this-php-call-to-json-encode-silently-failing-inability-to-handle-singl) – Prix Feb 24 '15 at 13:45
  • 1
    Yeah, the data that you are trying to encode probably contains non-utf8 characters. You should look into `utf8_encode()`. – Sverri M. Olsen Feb 24 '15 at 13:46
  • in the stackoverflow link @Prix gave, the 2nd answer listed seems helping too, by giving a link to php.net comments: http://php.net/manual/en/function.json-last-error.php#115980 – Asenar Feb 24 '15 at 14:25

1 Answers1

2

From PHP's manpage for json_last_error():

JSON_ERROR_UTF8 Malformed UTF-8 characters, possibly incorrectly encoded (PHP 5.3.3)

You have to ensure that the data given to json_encode() is UTF8, you should try using iconv to convert your strings to a proper format.

NaeiKinDus
  • 730
  • 20
  • 30
  • 1
    Well, Changed the MySQL Tables to handle UTF-8 Instead of 'latin1_swedish_ci' now the result set is reaching json_encode properly encoded to UTF-8. It's working – JuanBonnett Feb 24 '15 at 13:55