How to return JSON from a PHP Script?

Spread the love

Sometimes, we want to return JSON from a PHP Script.

In this article, we’ll look at how to return JSON from a PHP Script.

How to return JSON from a PHP Script?

To return JSON from a PHP Script, we can call the json_encode function.

For instance, we write

$data = [
      'profile_image_url' => 'https://picsum.photos/200/300',
      'screen_name' => 'mike',
      'text' => 'hello.',
      'timestamp' => 575859869,
];
header('Content-Type: application/json; charset=utf-8');
echo json_encode($data);

to call json_encode with $data to serialize the $data associative array into JSON.

We call header with 'Content-Type: application/json; charset=utf-8' to set the Content-Type response header to application/json so that it matches the data type of the data returned.

Conclusion

To return JSON from a PHP Script, we can call the json_encode function.

Leave a Reply

Your email address will not be published. Required fields are marked *