繁体   English   中英

使用 PHP 从 MySQL 获取 JSON 作为字符串,我们可以在字段中以 JSON 的形式获取数据吗

[英]Getting JSON as string from MySQL using PHP, can we get data as JSON in a field

我正在使用核心 PHP 开发 API。 当我返回数据时,所有字段数据都以字符串形式返回,但在某些字段中,我有 JSON 类型的数据,这些数据也以字符串形式返回

例子:

end_city: "mysore",
facilities: "{"Breakfast":false,"PickDrop":true,"Hotel":false,"Guide":true}"

在这里,现场设施有 JSON,但在响应中将其作为字符串获取,只想将其作为 JSON 而非字符串获取。

<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, DELETE, PUT');
header('Access-Control-Allow-Headers: token, Content-Type');

// get database connection
require_once '../config/database.php';

// instantiate tours object
include_once '../objects/tours.php';

$db = new Database();
$tours = new Tours($db);

$tour = $tours->getTour($_REQUEST["t"]);
$num = $tour->num_rows;

if ($num > 0) {
    while ($row = $tour->fetch_assoc()) {
        echo json_encode($row);
    }
    // set response code - 200 OK
    http_response_code(200);
} else {
    // set response code - 404 Not found
    http_response_code(404);
    // tell the user no products found
    echo json_encode(
        array("message" => "No tour found.")
    );
}

确切的情况是,我有一个表单,提交该表单后,我在某些字段中获取 JSON 数据,在获取所有数据后,我使用核心 php 将其保存在 mysql 中,现在我必须使用 angualrjs 在页面上显示该数据。 现在,当我收到 request 时,我以 JSON 格式获取数据,并且所有字段都是 string 类型,即使是我作为 string 获取的 JSON 字段也会产生问题。

使用json_decode将字符串转换为 json

https://www.php.net/manual/en/function.json-decode.php

  1. 在发送内容之前设置状态代码并发送标头。
  2. 不要在循环中回显多个 json 值,这不是有效的 json 响应。 将所有结果收集到一个列表中,对它进行 json_encode 然后发送。
  3. 将内容类型设置为application/json

改变:


if ($num > 0) {
    while ($row = $tour->fetch_assoc()) {
        echo json_encode($row);
    }
    // set response code - 200 OK
    http_response_code(200);

进入

header('content-type: application/json');
if ($num > 0) {
    http_response_code(200);
    $results = []
    while ($row = $tour->fetch_assoc()) {
        $results[] = $row;
    }
    echo json_encode($results);

上述问题已解决,问题是我的数据未正确保存在数据库中,这就是 JSON.parse 无法正常工作的原因,但现在使用 JSON.parse 解决了问题

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM