PHP JSON π
JSON (JavaScript Object Notation) is a lightweight data format used for exchanging data between a server and a client. PHP provides built-in functions to handle JSON data efficiently.
Why Use JSON in PHP?
β Easy to read and write π
β Works well with JavaScript π
β Lightweight and faster than XML β‘
β Used in APIs and web services π
Encoding PHP Data to JSON (json_encode)
You can convert a PHP array or object into a JSON string using json_encode()
.
$data = ["name" => "John", "age" => 25, "city" => "New York"];
$jsonData = json_encode($data);
echo $jsonData;
Output:
{"name":"John","age":25,"city":"New York"}
Decoding JSON to PHP (json_decode)
You can convert a JSON string back to a PHP array or object using json_decode()
.
$jsonString = '{"name":"John","age":25,"city":"New York"}';
$arrayData = json_decode($jsonString, true); // Converts to an associative array
echo $arrayData["name"];
Output:
John
If you omit true
, json_decode()
will return an object instead of an array.
$objectData = json_decode($jsonString);
echo $objectData->name;
Working with JSON in APIs
PHP JSON functions are commonly used in REST APIs, where data is exchanged in JSON format between a client (frontend) and a server (backend).
header("Content-Type: application/json"); // Set response type
$data = ["status" => "success", "message" => "Data fetched successfully"];
echo json_encode($data);
Summary
β
json_encode() → Converts PHP data to JSON
β
json_decode() → Converts JSON to PHP data
β
Used in APIs and web services
JSON in PHP makes data exchange seamless and efficient!
@asadmukhtar