Horje
How to Return JSON from a PHP Script ?

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




Reffered: https://www.geeksforgeeks.org


PHP

Related
How to JSON Decode in PHP? How to JSON Decode in PHP?
How to Remove First Element from an Array in PHP? How to Remove First Element from an Array in PHP?
How to Check if a Value Exists in an Associative Array in PHP? How to Check if a Value Exists in an Associative Array in PHP?
How to Check if a Key Exists in an Associative Array in PHP? How to Check if a Key Exists in an Associative Array in PHP?
How to Get All Keys of an Associative Array in PHP? How to Get All Keys of an Associative Array in PHP?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
17