php - json响应返回空

时间:2016-06-01 21:07:27

标签: php json encode

我在我的休息api中使用slim,这是一种get方法。当它被回显时,json数组是空的。

$app->get("/users", function () {

$response = array();
$db = new DbHandler();

// fetching all users
$result = $db->getAllUsers();

$response["error"] = false;
$response["users"] = array();

// looping through result and preparing users array
while ($user = $result->fetch_assoc()) {
    $tmp = array();
    $tmp["id_user"] = $user["id_user"];
    $tmp["name"] = $user["name"];
    array_push($response["users"], $tmp);
}
//var_dump($tmp);
//var_dump($response);

echoRespnse(200, $response);
});

var_dump完美地向我展示了数组,问题在于json_encode

编辑:这是echoResponse的代码

function echoRespnse($status_code, $response) {
    $app = \Slim\Slim::getInstance();
    $app->status($status_code);

    // setting response content type to json
    $app->contentType('application/json');

    echo json_encode($response);
}

编辑2 :$ response

的var_dump
array(2) {
  ["error"]=>
  bool(false)
  ["users"]=>
  array(8) {
    [0]=>
    array(2) {
      ["id_user"]=>
      int(1)
      ["name"]=>
      string(14) "Pedro Gonzalez"
    }
    [1]=>
    array(2) {
      ["id_user"]=>
      int(2)
      ["name"]=>
      string(14) "Juan Marcano"
    }
    [2]=>
    array(2) {
      ["id_user"]=>
      int(3)
      ["name"]=>
      string(12) "Ana Maria"
    }
    [3]=>
    array(2) {
      ["id_user"]=>
      int(4)
      ["name"]=>
      string(13) "Eduado Perez"
    }
    [4]=>
    array(2) {
      ["id_user"]=>
      int(5)
      ["name"]=>
      string(12) "Gilberto Perez"
    }
    [5]=>
    array(2) {
      ["id_user"]=>
      int(6)
      ["name"]=>
      string(12) "Roberto Perez"
    }
    [6]=>
    array(2) {
      ["id_user"]=>
      int(7)
      ["name"]=>
      string(12) "Juan Perez"
    }
    [7]=>
    array(2) {
      ["id_user"]=>
      int(8)
      ["name"]=>
      string(15) "Juanito Alimaña"
    }
  }
}

编辑3:我已经解决了这个问题。是关于数据库的charset,我已经将此代码添加到我的连接功能,它的工作现在就像一个魅力。

function connect() {
    include_once dirname(__FILE__) . './Config.php';

    // Connecting to mysql database
    $this->conn = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);

    // magic trick
    if (!$this->conn->set_charset("utf8")) {
         printf("Error cargando el conjunto de caracteres utf8: %s\n", $mysqli->error);
         exit();
    } else {
         printf("Conjunto de caracteres actual: %s\n", $this->conn->character_set_name());
    }

    // Check for database connection error
    if (mysqli_connect_errno()) {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

    // returing connection resource
    return $this->conn;
}

0 个答案:

没有答案