json_encode() to convert data to string

Json is a data exchange format like XML. You can learn about Json support of PHP here.

json_encode function takes data and converts them to a string, we call it as Json string. This string format follows a standard so it can be decoded back to its original data form at the receiving end.

Example 1 : PHP Class data

<?Php
$my_data = new stdClass();
$my_data->name="plus2net";
$my_data->area="PHP";
$my_data->section="Json";

$out_data=json_encode($my_data);
echo $out_data;
?>
Output is here
{"name":"plus2net","area":"PHP","section":"Json"}

Example 2 : PHP Array data

$a=array("Apple"=>10,"Orange"=>40,"Mango"=>80,"Banana"=>30);
echo json_encode($a);
The output of the above code is here.
{"Apple":10,"Orange":40,"Mango":80,"Banana":30}
This is one of the simple requirements, so we will try some complex than this by using two arrays.
<?Php
$my_data = new stdClass();
$my_data->name="plus2net";
$my_data->area="PHP";

$a=array("Apple"=>10,"Orange"=>40,"Mango"=>80);

$out_data=array($a,"data"=>$my_data);
echo json_encode($out_data);
?>
The output of the above code is here.
{"0":{"Apple":10,"Orange":40,"Mango":80},"data":{"name":"plus2net","area":"PHP"}}
You can start from here making your json string to exchange data across pages.
You can use database records to create JSons string and pass the data to different pages. Download the zip file to check the demo scripts using student table data to create Json string.



json data formatting
Json XML Ajax
Subhendu Mohapatra — author at plus2net
Subhendu Mohapatra

Author

🎥 Join me live on YouTube

Passionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.



Subscribe to our YouTube Channel here



plus2net.com











PHP video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer