When using PHP’s json_encode() function, you can encode a PHP array or object into a JSON string. The json_encode() function accepts an array or object as its argument and returns a string in JSON format.
Here is an example of using json_encode() function to encode a PHP array:
$data = array(
'name' => 'John Doe',
'age' => 30,
'email' => 'john@example.com'
);
$json = json_encode($data);
echo $json;
The output will be a JSON string:
{
"name": "John Doe",
"age": 30,
"email": "john@example.com"
}
You can also pass additional options to the json_encode() function to control the encoding behavior. For example, you can use the JSON_PRETTY_PRINT option to format the JSON string with indentation and line breaks for better readability:
$json = json_encode($data, JSON_PRETTY_PRINT);
echo $json;
The output will be a formatted JSON string:
{
"name": "John Doe",
"age": 30,
"email": "john@example.com"
}
