不要从php编码json

时间:2017-05-25 07:12:24

标签: php android json

我有2个文件php:connect.php和getsp.php。如下:

- Connect.php:

    $host = "localhost";
    $username = "root";
    $password = "";
    $database = "thietbi";

    $conn = mysqli_connect($host, $username, $password, $database);
    mysqli_query($conn, "SET NAMES 'uft8'");

- Getsp.php

include "connect.php";
// mysqli_set_charset($conn, "utf8");
$page = $_GET['page'];
$idsp = 1;  
$space = 5;     
$limit = ($page - 1) * $space;      

$mangsanpham = array();

$query = "SELECT * FROM sanpham WHERE idsanpham = $idsp LIMIT $limit,$space";       
$data = mysqli_query($conn,$query);

while ($row = mysqli_fetch_assoc($data)) {
    $id = $row['id'];
    $tsp = $row['tensanpham'];
    $gsp = $row['giasanpham'];
    $hsp = $row['hinhanhsanpham'];
    $mtsp = $row['motasanpham'];
    $isp = $row['idsanpham']));

    array_push($mangsanpham, new Sanpham($id, $tsp, $gsp, $hsp, $mtsp, $isp));
}

echo json_encode($mangsanpham);

class Sanpham{
    function Sanpham($id, $tensp, $giasp, $hinhsp, $motasp, $idsanpham){
        $this->id = $id;
        $this->tensp = $tensp;
        $this->giasp = $giasp;
        $this->hinhsp = $hinhsp;
        $this->motasp = $motasp;
        $this->idsanpham = $idsanpham;
    }
}

当我运行文件" Getsp.php"时,结果为白色空白页。

我用内容替换getsp.php:

include "connect.php";
// mysqli_set_charset($conn, "utf8");
$page = $_GET['page'];
$idsp = 1;  
$space = 5;     
$limit = ($page - 1) * $space;      

$mangsanpham = array();
$query = "SELECT * FROM sanpham WHERE idsanpham = $idsp LIMIT $limit,$space";       
$data = mysqli_query($conn,$query);

while ($row = mysqli_fetch_assoc($data)) {
    array_push($mangsanpham, new Sanpham(
    $row['id'],
    $row['tensanpham'],
    $row['giasanpham'],
    $row['hinhanhsanpham'],
    $row['motasanpham'],
    $row['idsanpham']));
}

echo json_encode($mangsanpham);

class Sanpham{
    function Sanpham($id, $tensp, $giasp, $hinhsp, $motasp, $idsanpham){
        $this->id = $id;
        $this->tensp = $tensp;
        $this->giasp = $giasp;
        $this->hinhsp = $hinhsp;
        $this->motasp = $motasp;
        $this->idsanpham = $idsanpham;
    }
}

结果不是。我哪里错了? 我试过两种方法:

$json = json_encode($mangsanpham, JSON_PRETTY_PRINT);
print_r($json);

echo json_encode($mangsanpham);

结果不是编码JSON。希望得到大家的帮助!

1 个答案:

答案 0 :(得分:2)

要使用array_push,必须将第一个变量声明为数组 即$ mangsanpham = array(); //在while循环之前