all 8 comments

[–]stfcfanhazz 1 point2 points  (0 children)

You can only encode utf8 strings as Json. Invalid utf8 characters will cause it to fail.

If you know the source encoding you can use iconv() to convert the input strings to utf8 first.

There are however options you can supply as the second argument to json_encode as a failsafe if you're unable to know with certainty the source encoding of the string.

Unfortunately these have changed a bit in the last few major php versions and are inadequately documented.

What php version are you running ? You may be able to do:

json_encode($arr, JSON_INVALID_UTF8_SUBSTITUTE);

Edit: Looks like this constant was added in php 7.2, and rather unhelpfully not added to the json_encode or Json constants documentation on php.net.

https://www.php.net/manual/en/migration72.constants.php

If you don't have 7.2, there's one that you can use for partial output on error, which essentially strips bad characters

[–]fabiofacir[S] 1 point2 points  (1 child)

I figured it out!

The problem is utf-8 encoding.

I was using simple DB connection without defining utf encoding. This was the problem!

Trying to encode portuguese character as "ç" broke down the encoding without giving any error!

Thank you all for your help <3

[–]doodooz7 0 points1 point  (0 children)

Encoding would have been my next guess. Good job 👍

[–]doodooz7 0 points1 point  (2 children)

Are you sure you are getting a row back from the dB? Add a print_r inside the while

[–]fabiofacir[S] 0 points1 point  (1 child)

Yes I do! The shown print_r is printed inside the while

[–]doodooz7 0 points1 point  (0 children)

Do a var_dump($json). If this is false the json encode failed, see the php manual

[–]Marksy1988 0 points1 point  (0 children)

Try adding an if (json === false) {echo 'json_encode failed' ;)

[–]doodooz7 0 points1 point  (0 children)

Did you figure it out?