PHP json_encode() function is “used to convert a PHP array or object into a JSON-formatted string”.
Syntax
json_encode($value, $options, $length)
Parameters
$value(required): It is the value to be encoded.
$options(optional): It is a Bitmask comprising of JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP,JSON_HEX_APOS,JSON_NUMERIC_CHECK,JSON_PRETTY_PRINT,JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT,among others.
$length(optional): Sets the maximum depth, which must be greater than zero.
Return Value
This function returns a JSON formatted string on success or false on failure.
Visual Representation of Using an indexed array
Example 1: How to Use json_encode() Function
<?php
$arr = array("name" => "David", "age" => 32, "country" => "USA");
echo json_encode($arr)."\n";
Output
{"name":"David","age":32,"country":"USA"}
with JSON_PRETTY_PRINT
<?php
$arr = array("name" => "David", "age" => 32, "country" => "USA");
echo json_encode($arr,JSON_PRETTY_PRINT)."\n";
Output
{
"name": "David",
"age": 32,
"country": "USA"
}
Example 2: PHP Object to JSON
<?php
class App {
}
$app = new App();
$app->title = 'Harry Potter Game';
$app->price = 20;
$jsonData = json_encode($app);
echo $jsonData."\n";
Output
{"title":"Harry Potter Game","price":20}
Example 3: Using an indexed array
<?php
$arr = array('Ronaldo','Messi','Mbappe','Neymar');
echo json_encode($arr)."\n";
Output
["Ronaldo","Messi","Mbappe","Neymar"]
That’s it.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.
Nice Explanation, I was doubt about JSON but now clear.
Thank you Krunal!
This is a great blog post! I’ve been wanting to learn more about how to use PHP json_encode() and this post has really helped me understand the function better.
Thanks you save my time a lot