php
Return JSON from a PHP script
October 3, 2022
To return JSON data from you PHP script you can use json_encode() function. It will convert PHP array to JSON string.
<?php
// set header
header('Content-Type: application/json');
// create a php array
$myarr = [
[ "id" => 1, "name" => "Math" ],
[ "id" => 1, "name" => "physics" ],
[ "id" => 1, "name" => "Chemistry" ]
];
// convert to json and print
echo json_encode($myarr);
?>
To return JSON from a PHP script you can set its header to 'Content-Type: application/json'.
This will return data in JSON format as your API response.
Was this helpful?
Similar Posts