Returning JSON from a PHP script

Nadia S.

The Problem

How can I return JSON from a PHP script?

The Solution

We use the header() function to set Content-Type to application/json. Then we can use the json_encode() function to covert our PHP array into a JSON-formatted string. For example:

Click to Copy
<?php // Set the header content-type header('Content-Type: application/json'); // Create or get a PHP array (or object) $array = [ 'Canada' => 'Ottawa', 'India' => 'New Delhi', 'United States' => 'Washington, D.C.', 'France' => 'Paris', ]; // Encode to JSON format $json = json_encode($array, JSON_PRETTY_PRINT); // Display echo $json;

As a second argument, we use JSON_PRETTY_PRINT to add spaces to improve the readability of the output. For example:

Click to Copy
{ "Canada": "Ottawa", "India": "New Delhi", "United States": "Washington, D.C.", "France": "Paris" }

While it’s not essential to set the header content type to application/json, it’s recommended as a best practice. Especially when you’re working with APIs and various services, explicitly communicating to the client that the response will be in JSON format ensures the data is correctly handled and processed.

Loved by over 4 million developers and more than 90,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.

Share on Twitter
Bookmark this page
Ask a questionJoin the discussion

Related Answers

A better experience for your users. An easier life for your developers.

    TwitterGitHubDribbbleLinkedinDiscord
© 2024 • Sentry is a registered Trademark
of Functional Software, Inc.