简体   繁体   中英

How to get a JSON response using PHP?

I am learning to create an API to return JSON for my Android App. 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

$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.

Thanks in Advance

This is my PHP File (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. You can transform it with functions utf8_encode (if data is ISO-8859) or iconv.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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