1

I was trying to get the response from an SQL select statement but when I try to echo the array encoded to JSON I don't have anything written except the "-" I echo to ensure myself that is entering into the loop.

$sql = "SELECT * FROM PREGUNTA WHERE PREGUNTA.pregunta LIKE '%$palabra_clave%' OR PREGUNTA.respuesta_correcta LIKE '%$palabra_clave%' OR PREGUNTA.respuesta_falsa_1 LIKE '%$palabra_clave%' OR PREGUNTA.respuesta_falsa_2 LIKE '%$palabra_clave%' OR PREGUNTA.retroalimentacion LIKE '%$palabra_clave%'";
$query = mysqli_query($con, $sql);

$json = array();

while($data = $query->fetch_assoc()){
  $json[] = array(
      'pregunta' => $data['pregunta'],
      'respuesta_correcta' => $data['respuesta_correcta'],
      'respuesta_falsa_1' => $data['respuesta_falsa_1'],
      'respuesta_falsa_2' => $data['respuesta_falsa_2'],
      'retroalimentacion' => $data['retroalimentacion']
  );

    echo $data['pregunta'];
    echo '<br>';
}

echo json_encode($json);

And I this is my output:

¿Cuál no es un lenguaje de programación web?
¿Cuál es el lenguaje web más importante?
Juan Manuel Amoros
  • 347
  • 1
  • 5
  • 17

1 Answers1

3

Most likely your input does not use the UTF-8 character encoding. According to the documentation for json_encode "All string data must be UTF-8 encoded".

When I pass an array containing "¿Cuál no es un lenguaje de programación web?" to json_encode, it works fine. But if I first convert the text to ISO-8859-1, json_encode returns boolean false and therefore outputs nothing.

Assign your variables to the array with (eg):

$json[] = array('pregunta' =>
    mb_convert_encoding($data['respuesta_correcta'], 'UTF-8', 'ISO-8859-1'),
    // ...
);

or convert your database and application to use UTF-8 to start with.

Matt Raines
  • 4,149
  • 8
  • 31
  • 34
  • That was the problem. Now it works really good converting the encoding, but the server conection is in UTF8_general_ci, the database is in UTF8-spanish_ci and the tables are in UTF8-spanish_ci. Do you have any idea why I am having this problem? – Juan Manuel Amoros Mar 15 '16 at 15:18
  • Have a browse through [UTF-8 all the way through](http://stackoverflow.com/questions/279170/utf-8-all-the-way-through). Chances are something in your stack isn't configured to use UTF-8 correctly. – Matt Raines Mar 15 '16 at 15:22