douzhang1364 2013-05-17 01:32 采纳率: 0%
浏览 96

如何使用PHP正确输出JSON数据

I'm developing an Android app, and for the API I'm sending my requests to a URL that should return JSON data.

This is what I'm getting in my output: My response

And I'd like it to be displayed as Twitter response:

Twitter's JSON response

I'm assuming my response is not being parsed by the JSON Formatter Chrome extension because it's encoded badly, thus my app can't get the values I need.

Here's my PHP code:

<?php

$response = array();

if (isset($_POST['name']) && isset($_POST['price']) && isset($_POST['description'])) 
{

    $name = $_POST['name'];
    $price = $_POST['price'];
    $description = $_POST['decription'];

    require_once __DIR__ . '/db_connect.php';

    $db = new DB_CONNECT();

    $result = mysql_query("INSER INTO products(name, price, description) VALUES('$name', '$price', '$description')");

    if ($result) {
        $response["success"] = 1;
        $response["message"] = "Product successfully created.";

        echo json_encode($response);
    } else {

        $response["success"] = 0;
        $response["message"] = "Oops! An error occurred!";

        echo json_encode($response);
        }
} else {

    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";

    echo json_encode($response);

}

?>

I want to know how to display the JSON data correctly so that JSON Formatter and my android App can parse it correctly.

  • 写回答

7条回答 默认 最新

  • dos71253 2013-05-17 01:51
    关注

    PHP's json_encode function takes a second argument, for $options. Here you can use JSON_PRETTY_PRINT to print it like you see in the Twitter API

    E.g.

    echo json_encode($my_array, JSON_PRETTY_PRINT);
    
    评论

报告相同问题?