PHP echo json始终为空值

问题描述 投票:0回答:2

我试图用PHP从mysql数据库返回一些值作为JSON。

我尝试了很多方法,我认为我的代码是正确的,但它总是返回空白。

这样我可以看到返回的值:

echo $row['name'];

但是当我使用时

json_encode

它返回空白。

这是我的代码:

<?php
// $dbconfig = require_once('../config.php');
require_once('../DBConnection.php');

// $database = new DBConnection($dbconfig);
// $sqlSelect = "select * from Estados";
// $rows = $database->getQuery($sqlSelect);

$response = array();

class EstadoDAO {

    public function getEstados($dbconfig) {

        $sqlSelect = "select * from Estados";
        $database = new DBConnection($dbconfig);

        try {
            $rows = $database->getQuery($sqlSelect);
            if ($rows) {
                $response["estado"] = array();
                foreach($rows as $row){
                    //echo $row['name']; // IT WORKS
                    $estado = array();
                    $estado['name'] = $row['name'];

                    array_push($response["estado"], $estado);
                }
            } else {
                //zero linhas
                $estado = array();
                $estado['name'] = $row['ERRO'];

                array_push($response["estado"], $estado);
            }

        } catch (Exception $e) {

        }

        $database->__destruct();
        echo json_encode($response);
    } //function
}// Class

编辑1

var_dump响应:

array(1) { ["estado"]=> array(3) { [0]=> array(1) { ["name"]=> string(17) "Rio Grande do Sul" } [1]=> array(1) { ["name"]=> string(14) "Santa Catarina" } [2]=> array(1) { ["name"]=> string(6) "Paran�" } } }
php json
2个回答
1
投票

这可能是因为你的记录中有未转义的unicode。

使用json_encode($response, JSON_UNESCAPED_UNICODE)

所有字符串数据必须采用UTF-8编码。

http://php.net/manual/en/function.json-encode.php


0
投票

需要使用它

函数utf8_encode

这是答案:

foreach($rows as $row){
    //echo $row['name']; // IT WORKS
    $estado = array();
    $estado['name'] = utf8_encode($row['name']);

    array_push($response["estado"], $estado);
}
© www.soinside.com 2019 - 2024. All rights reserved.