PHP:
Working with JSON
How to:
Working with JSON in PHP is straightforward thanks to the built-in functions json_encode()
and json_decode()
. Below are examples showcasing how to convert a PHP array into a JSON string, and vice versa:
Encoding a PHP Array into a JSON String
// Define an associative array
$data = [
"name" => "John Doe",
"age" => 30,
"email" => "[email protected]"
];
// Convert the PHP array to a JSON string
$jsonString = json_encode($data);
// Output the JSON string
echo $jsonString;
Sample Output:
{"name":"John Doe","age":30,"email":"[email protected]"}
Decoding a JSON String into a PHP Array
// JSON string
$jsonString = '{"name":"John Doe","age":30,"email":"[email protected]"}';
// Convert the JSON string to a PHP array
$data = json_decode($jsonString, true);
// Output the PHP array
print_r($data);
Sample Output:
Array
(
[name] => John Doe
[age] => 30
[email] => [email protected]
)
Working with a Third-Party Library: GuzzleHttp
For complex JSON and web request handling, one popular PHP library is GuzzleHttp. It simplifies HTTP requests and easily works with JSON data.
Installation via Composer:
composer require guzzlehttp/guzzle
Example Request:
require 'vendor/autoload.php';
use GuzzleHttp\Client;
$client = new Client();
// Send a request to an API that returns JSON
$response = $client->request('GET', 'https://api.example.com/data', [
'headers' => [
'Accept' => 'application/json',
],
]);
// Decode the JSON response to a PHP array
$data = json_decode($response->getBody(), true);
// Output the data
print_r($data);
Assuming the API returns similar JSON data:
Array
(
[name] => John Doe
[age] => 30
[email] => [email protected]
)
This showcases the ease of using PHP for JSON manipulation, both with native functions and with robust libraries like GuzzleHttp for more complex tasks.