Open In App

How to Return JSON from a PHP Script ?

Last Updated : 17 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Returning JSON Data consists of converting PHP data structures like arrays or objects into a JSON format. In this article, we will explore two different approaches to Return JSON from a PHP Script.

Below are the approaches to Return JSON from a PHP Script:

Using json_encode()

In this approach, we are using json_encode() to convert a PHP associative array ($jsonData) containing organization, founder, and employee data into JSON format. The header(‘Content-Type: application/json’) sets the response header to indicate that the content being sent is JSON data.

Example: The below example uses json_encode() to Return JSON from a PHP Script.

PHP
<?php
$jsonData = array(
    'organization' => 'GeeksforGeeks',
    'founder' => 'Sandeep Jain',
    'employee' => 'Gaurav'
);
header('Content-Type: application/json');
echo json_encode($jsonData);
?>

Output:

{
 "organization": "GeeksforGeeks",
 "founder": "Sandeep Jain",
 "employee": "Gaurav"
}

Using file_get_contents()

In this approach, we are using file_get_contents() to fetch JSON data from the specified URL ($jsonPlaceholderUrl), which in this case is the JSONPlaceholder API. The header(‘Content-Type: application/json’) sets the response header to indicate that the content being sent is JSON data, and echo $response outputs the fetched JSON data.

Example: The below example uses file_get_contents() to Return JSON from a PHP Script.

PHP
<?php
$jsonPlaceholderUrl = 
'https://jsonplaceholder.typicode.com/posts/1';
$response = file_get_contents($jsonPlaceholderUrl);
header('Content-Type: application/json');
echo $response;
?>

Output:

{
 "userId": 1,
 "id": 1,
 "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
 "body": "quia et suscipit\nsuscipit repellat...
}

GIF:

1


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads