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

Osc*_*ros 14 php android json

我正在开发一个Android应用程序,对于API,我将我的请求发送到应该返回JSON数据的URL.

这是我在输出中得到的: 我的回复

我希望它显示为Twitter响应:

Twitter的JSON响应

我假设我的响应没有被JSON Formatter Chrome扩展程序解析,因为它的编码很糟糕,因此我的应用程序无法获得我需要的值.

这是我的PHP代码:

<?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);

}

?>
Run Code Online (Sandbox Code Playgroud)

我想知道如何正确显示JSON数据,以便JSON Formatter和我的Android应用程序可以正确解析它.

Cha*_*zin 16

你的问题实际上很容易解决.如果Content-Type标头设置为application/json,则Chrome JSON Formatter插件仅格式化您的输出.

您需要在代码中更改的唯一方法是header('Content-Type: application/json');在返回json编码数据之前在PHP代码中使用.

  • 我知道这个问题具体说明了chrome等,但是我发现要在FF中使用它,我必须使用`header('Content-Type:application/json');`而不是`header('Content-Type' ,'application/json');`(用冒号替换逗号) (2认同)

jra*_*ede 5

PHP的json_encode函数接受第二个参数$options.在这里,您可以JSON_PRETTY_PRINT像在Twitter API中看到的那样打印它

例如

echo json_encode($my_array, JSON_PRETTY_PRINT);
Run Code Online (Sandbox Code Playgroud)