Array is not converted to JSON

1

I handle some functions via PHP and in the end I return the AJAX client with useful information. Such information is contained in an array that is converted to JSON by json_encode() . The problem is that I get sent an error message with the following:

  

SyntaxError: Unexpected end of input

This error happens because json_encode() is not returning any array . I have my variable:

$data = array(
    'command' => $command,
    'message' => $message
);

And the result of var_dump for json_encode() is as follows (I put the HTML code for better visualization, execute it):

<pre class='xdebug-var-dump' dir='ltr'><small>boolean</small> <font color='#75507b'>false</font>
</pre>

The problem only happens when the value of the variable $message is coming from an error in the database, if I write anything in it, the return is normal:

<pre class='xdebug-var-dump' dir='ltr'><small>string</small> <font color='#cc0000'>'{&quot;command&quot;:2,&quot;message&quot;:&quot;Qualquer coisa&quot;}'</font> <i>(length=40)</i>
</pre>{"command":2,"message":"Qualquer coisa"}

Here is the var_dump of an example of a return of the variable $message :

<pre class='xdebug-var-dump' dir='ltr'><small>string</small> <font color='#cc0000'>'Erreur de syntaxe pr�s de &#39;&#39;NomeDeUsuario&#39;, &#39;$2a$05$Zx3hjrLOnWvNzZpRIhdcPecjreTjjaBkaYLrH7IRcfmn110et/92G&#39;,&#39; � la ligne 1'</font> <i>(length=121)</i>
</pre>

Notice that this is an error in the database. The error itself is not relevant, I even caused it to test the return of errors to the client.

    
asked by anonymous 21.04.2015 / 21:34

1 answer

2

By error Erreur de syntaxe pr�s with this character , I suppose you are trying to pass a string that uses iso-8859-1 (latin) instead of utf-8 , your page is likely to be utf8, but there are files including using iso-8859-1

To solve it more easily, you can convert the string to utf-8 first:

$data = array(
    'command' => $command,
    'message' => $message
);

$data = utf8_encode($data);

echo json_encode($data);

Details:

Your bank may even be in utf-8, but it may be that the way you made the connection may be bringing in some files and may be using ANSI with iso-8859-1 accents, please read this link help standardize your project:

21.04.2015 / 21:38