gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 00:03:18 25 4
gpt4 key购买 nike

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

这是我在输出中得到的: My response

我希望它显示为 Twitter 回复:

Twitter's JSON response

我假设我的响应没有被 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);

}

?>

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

最佳答案

你的问题其实很容易解决。如果 Content-Type header 设置为 application/json,Chrome JSON Formatter 插件只会格式化您的输出。

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

关于php - 如何使用PHP正确输出JSON数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16600099/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com