简体   繁体   中英

How to return json data to client from PHP?

I have tried this:

<?php

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
  return json_decode(file_get_contents("categories.json"), true);
}

Where categories.json contains:

[{ "name": "Супа", "id": 1641043113893 }, { "name": "Гарниры", "id": 1641043121942 }, { "name": "Горячее", "id": 1641043128276 }, { "name": "Выпечка", "id": 1641043135885 }, { "name": "Десерты", "id": 1641043141125 }, { "name": "Салаты", "id": 1641043146356 }]

Why I can not get this json object on the client side when I send GET request?

You should use echo to output the json string and also use proper HTTP Content-Type Header.

Note that you use the json_decode it will output an associative array, you may json_encode it again to make json string.

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");

// Content Type
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    echo json_encode(json_decode(file_get_contents("categories.json"), true));
}

Or you can just echo file_get_contents("categories.json");

Duplicate question: Returning JSON from a PHP Script

You need a couple things:

Need a content type header:

header('Content-Type: application/json; charset=utf-8');

Also do not "decode" the JSON string. Just echo it:

echo file_get_contents("categories.json");

Issue is json_decode is making an array (with true flag), json encode makes a string.

If the file is in json format already you would just output it directly.

echo file_get_contents(‘fn.json’);

You're also using return vs echo.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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