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.
    // 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?
Programming Feeds
Learn something new everyday on Devsheet