# Return JSON from a PHP Script with json_encode

> Set the Content-Type header to application/json and use json_encode() to convert PHP arrays into JSON-formatted responses with optional pretty printing

**URL:** https://sentry.io/answers/returning-json-from-a-php-script/

---

## 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:

```php
<?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:

```
{
    "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.

---

*Source: [sentry.io/answers/returning-json-from-a-php-script/](https://sentry.io/answers/returning-json-from-a-php-script/)*
