json_encode
is a function in PHP that is used to encode a PHP data structure (such as an array or an object) into a JSON string.
JSON stands for JavaScript Object Notation, and it is a lightweight data interchange format that is easy for humans to read and write, and easy for machines to parse and generate.
Php json_encode example
Here’s a basic example of how json_encode
works in PHP:
<?php
// Define a PHP associative array
$person = array(
'name' => 'John Doe',
'age' => 30,
'city' => 'New York'
);
// Encode the array into a JSON string
$jsonString = json_encode($person);
// Output the JSON string
echo $jsonString;
?>
{"name":"John Doe","age":30,"city":"New York"}
- We have a PHP associative array called
$person
containing some information about a person. - We use the
json_encode
function to convert this array into a JSON string. - The resulting JSON string contains the same data as the original PHP array, but it is formatted as a string in JSON format.
- Finally, we output the JSON string using
echo
.
json_encode
can handle nested arrays and objects as well. It automatically converts PHP objects into associative arrays before encoding them as JSON.
Php json_encode array
Here’s another example with a nested array:
In this example, the $data
array contains a nested array of hobbies. json_encode
correctly encodes the entire structure into a JSON string.
<?php
// Define a nested PHP array
$data = array(
'name' => 'John Doe',
'age' => 30,
'city' => 'New York',
'hobbies' => array('reading', 'swimming', 'coding')
);
// Encode the array into a JSON string
$jsonString = json_encode($data);
// Output the JSON string
echo $jsonString;
?>
{"name":"John Doe","age":30,"city":"New York","hobbies":["reading","swimming","coding"]}