Search code snippets, questions, articles...

Return JSON from a PHP script

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);
?>
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place.

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?
0 Comments