简体   繁体   English

如何使用PHP获得JSON响应?

[英]How to get a JSON response using PHP?

I am learning to create an API to return JSON for my Android App. 我正在学习创建一个API以为我的Android应用返回JSON。 http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/ http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/

I am not getting the JSON response if i add this line 如果添加此行,则无法获取JSON响应

$product["Area"] = $row["Area"];

If i remove the Above line from the below file. 如果我从下面的文件中删除上述行。 Then i am getting the response. 然后我得到了回应。

I have even checked the DB. 我什至检查了数据库。 This is how my DB looks like http://i.imgur.com/Cr4VmGW.png I can't figure it why it happens. 这就是我的数据库的外观,就像http://i.imgur.com/Cr4VmGW.png一样。我不知道为什么会这样。

Thanks in Advance 提前致谢

This is my PHP File (get_all_products) 这是我的PHP文件 (get_all_products)

<?php

/*
 * Following code will list all the products
 */

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


// include db connect class
require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();

// get all products from products table
$result = mysql_query("SELECT * FROM shelter") or die(mysql_error());

// check for empty result
if (mysql_num_rows($result) > 0) {
    // looping through all results
    // products node
    $response["products"] = array();

    while ($row = mysql_fetch_array($result)) {
        // temp user array
        $product = array();
        $product["ID"] = $row["ID"];
        $product["Timestamp"] = $row["Timestamp"];
        $product["Accomodation"] = $row["Accomodation"];
        $product["Area"] = $row["Area"];

        // push single product into final response array
        array_push($response["products"], $product);
    }
    // success
    $response["success"] = 1;

    // echoing JSON response
    echo json_encode($response);
} else {
    // no products found
    $response["success"] = 0;
    $response["message"] = "No products found";

    // echo no users JSON
    echo json_encode($response);
}
?>

json_encode() works with UTF8 strings, may be $row["Area"] has another codification. json_encode()适用于UTF8字符串,可能是$ row [“ Area”]具有另一个编码。 You can transform it with functions utf8_encode (if data is ISO-8859) or iconv. 您可以使用utf8_encode函数(如果数据为ISO-8859)或iconv对其进行转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM