PHP中的json_encode没有返回任何结果

时间:2015-04-07 23:04:08

标签: php android mysql arrays json

我有一个从我的数据库中检索一些数据的PHP脚本,我想在json中对其进行编码,以便在我的Android应用程序中进行处理。我希望结果如下:

{
    "part": [
        {
            "partNo": "value",
            "partName": "value",
            "shortDesc": "value",
            "longDesc": "value",
            "image": "value"
        },
        {
            "partNo": "value",
            "partName": "value",
            "shortDesc": "value",
            "longDesc": "value",
            "image": "value"
        }
    ],
    "success": 1
}

我正在使用以下PHP脚本。

// array for JSON response
$response = array();

// execute query based on specified user input
$result = mysql_query($sql) or die(mysql_error());

// check to see if results were found
if (mysql_num_rows($result) > 0) {
    //create a part array in $response to hold the part details
    $response['part'] = array();
    while ($row = mysql_fetch_array($result)) {
        //create an array for the part details
        $part = array();
        $part['partNo'] = $row['partNo'];
        $part['partName'] = $row['partName'];
        $part['shortDesc'] = $row['shortDesc'];
        $part['longDesc'] = $row['longDesc'];
        $part['image'] = "data:image/jpeg;base64,".base64_encode($row['image']);

        // put the array results for a single part in $response
        array_push($response['part'], $part);
    }
    // add the code for success to $response
    $response['code'] = 1;

    // and send it in json
    echo(json_encode($response));
    //print_r($response);
    //print_r(json_encode($response));
} else {
        //no results found
        $response['code'] = 0;
        $response['message'] = "No part found!";
        echo json_encode($response);
}

?>

我没有得到echo (json_encode($response));print_r(json_encode($response));的任何回复。但当我print_r($response);时,我得到了回复!

Array ( [part] => Array ( [0] => Array ( [partNo] => value [partName] => value [shortDesc] => value [longDesc] => value [image] => data:image/jpeg;base64,/9j/4QAYRXhpZgAAS.../9k= ) ) [code] => 1 )

有人可以对此有所了解吗?为什么不能使用json_encode?

1 个答案:

答案 0 :(得分:1)

只需使用以json格式返回$response

header('Content-type: application/json');
echo json_encode($response);