如何使用PHP正确输出JSON数据 [英] How to output JSON data correctly using PHP

查看:277
本文介绍了如何使用PHP正确输出JSON数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

我希望将其显示为Twitter响应:

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

我假设JSON Formatter Chrome扩展程序未对我的响应进行解析,因为它的编码错误,因此我的应用无法获得所需的值.

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.

这是我的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);

}

?>

我想知道如何正确显示JSON数据,以便JSON Formatter和我的android App可以正确解析它.

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

推荐答案

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

Your problem is actually very easy to solve. The Chrome JSON Formatter plugin only formats your output if the Content-Type header is set to application/json.

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

The only thing you need to change in your code is to use header('Content-Type: application/json'); in your PHP code, before returning the json-encoded data.

这篇关于如何使用PHP正确输出JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆