In this article, we will explain to you how to encode and decode JSON data in PHP. the JSON is an intermediate language because we can easily to use readable, and lightweight in any language. here we will give you a simple example of how to encode and decode JSON data in PHP.
JSON is JavaScript Object Notation. JSON is a lightweight data format used to communicate data from a server to a client-side.
we sometimes need to parse the JSON file in PHP. In the following code sample, you will learn how you can print data from JSON files in PHP.
{
"first_name":"abc",
"last_name":"xyz",
"gender":"Male"
}
We have the following script to read the generated JSON file and print the required output above:
<?php
$data = file_get_contents ('here add JSON Path');
$json = json_decode($data, true);
echo ('<pre>');
print_r ($json);
echo ('</pre>');
echo $json->first_name;
echo $json->last_name;
echo $json->gender;
?>
<?php
$data = array('first_name'=>'abc','last_name'=>'xyz','gender'=>'Male');
echo json_encode($data);
//output
{"first_name":"abc","last_name":"xyz","gender":"Male"}
?>
We can easily convert JSON data in PHP and print the variable. so you can see our example.
<?php
$data = '{"first_name":"abc","last_name":"xyz","gender":"Male"}';
$json = json_decode($data, true);
echo ('<pre>');
print_r ($json);
echo ('</pre>');
echo $json->first_name;
echo $json->last_name;
echo $json->gender;
?>