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);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大