The json_encode() function in PHP is a built-in function that converts PHP values into JSON format. JSON, or JavaScript Object Notation, is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate.
The json_encode() function takes a single argument, which is the value to be encoded. The value can be any PHP type, including arrays, objects, strings, integers, floats, and booleans. The function returns a string containing the JSON representation of the value.
// Define an array of ships $ships = array( array("name" => "Titanic", "type" => "passenger", "sunk" => true), array("name" => "Bismarck", "type" => "battleship", "sunk" => true), array("name" => "Enterprise", "type" => "aircraft carrier", "sunk" => false) ); // Encode the array as a JSON string $json = json_encode($ships); // Print the JSON string echo $json; Output: [{"name":"Titanic","type":"passenger","sunk":true},{"name":"Bismarck","type":"battleship","sunk":true},{"name":"Enterprise","type":"aircraft carrier","sunk":false}]
This example shows how the php json_encode function converts an array of associative arrays into a JSON array of objects. Each object has three properties: name, type, and sunk. The boolean values are encoded as true or false in JSON.
Encoding an Object:
This example encodes an object of the Ship class into JSON format.
class Ship { public $name; public $capacity; public function __construct($name, $capacity) { $this->name = $name; $this->capacity = $capacity; } } $ship = new Ship("Queen Mary", 2000); $json = json_encode($ship); echo $json; Output: {"name":"Queen Mary","capacity":2000}
Array to JSON array
$students = array( array('name' => 'John', 'age' => 20, 'grade' => 'A'), array('name' => 'Alice', 'age' => 22, 'grade' => 'B') ); $json_students = json_encode($students); echo $json_students; Output: [{"name":"John","age":20,"grade":"A"},{"name":"Alice","age":22,"grade":"B"}]
Here, we have an array of student records. json_encode will convert it into a JSON array.
Array to JSON string
$ship = [ "name" => "Evergreen", "type" => "Container ship", "capacity" => 20000, "builtYear" => 2019 ]; $jsonString = json_encode($ship); echo $jsonString; This code will output the following JSON string: {"name":"Evergreen","type":"Container ship","capacity":20000,"builtYear":2019}