json_encode() converts PHP arrays and objects into JSON. JSON_THROW_ON_ERROR is useful when an encoding failure should not be silently ignored.
<?php
$data = [
'name' => 'Alex',
'marks' => [78, 84, 91],
];
echo json_encode($data, JSON_THROW_ON_ERROR);
?>Current example first; the detailed examples below are retained for additional learning and comparison.
<?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"}
$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.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.