Netox
Netox

Reputation: 45

JSON/PHP - Empty Array

I'm trying to display JSON in my PHP file. The problem is that it doesn't show anything, like it was empty.

Code

<?php
include ('conexion.php');
//$id = $_GET['id'];
$sql = "SELECT tbl_usuarios.idUsuario, tbl_usuarios.nombrec, tbl_actividades.idUsuario, tbl_actividades.fec_actividad, tbl_actividades.nombre FROM tbl_actividades INNER JOIN tbl_usuarios ON tbl_usuarios.idUsuario = tbl_actividades.idUsuario WHERE tbl_usuarios.idUsuario = 1";

if($conexion){

    if(!$result = mysqli_query($conexion,$sql)) die();

        while($data = mysqli_fetch_array($result)){
            $arreglo[] = $data;
        }
        echo json_encode($arreglo);
    }else{
        die ("error");
    }

?>

It only shows when I use print_r($arreglo).

Upvotes: 0

Views: 56

Answers (1)

Edinson Sanchez
Edinson Sanchez

Reputation: 36

Some of your database objects are in Spanish, it is most probable that your result array, $arreglo is not encoded in utf-8. Because to Spanish uses special characters like 'ñ', it is most probable your default database encoding is not utf-8. When such characters are encountered, the function json_encode fails and shows nothing. Because such function only works with utf-8 results.

One way to deal with this is to pass your array through this function so it cast everything into utf-8. add the following function to your PHP.

 function cast_data_types ($value) {
      if (is_array($value)) {
        $value = array_map('cast_data_types',$value);
        return $value;
      }
      if (is_numeric($value)) {
        if(strpos('.', $value)===false) return (float)$value;
        return (int) $value;
      }
      return utf8_encode((string)$value);
    }

You can also apply JSON_UNESCAPED_UNICODE to properly show special characters back.

so instead of echo json_encode($arreglo);

you should input echo json_encode(cast_data_types($arreglo),JSON_UNESCAPED_UNICODE);

If the above does not work you can always use json_last_error() to check what error was encountered during json_encode or json_decode operations.

http://php.net/manual/es/function.json-last-error.php

Upvotes: 1

Related Questions