Php has built-in support for json. It has four json functions. They are

For example, if you need an array of json string ,create array in php and pass that array inside the json_encode function.


<?php

$cars=array("Jaguar","Benz","BMW");

echo json_encode($cars);

?>

output:

["Jaguar","Benz","BMW"]

If you need to generate key value pair, then create an array with key value pair.


<?php

$stack = array("name"=>"raja","age"=>25);

   echo json_encode($stack);

?>
Output:

{"name":"raja","age":25}

We can create json from php object. The Emp class has two public members. They are name and age of an employee.Then create an object for Emp class and set values for those variables and pass the object inside json_encode.


<?php
class Emp {
      public $name = "";
      public $age  = 0;
      
   }

    $e = new Emp();
   $e->name = "raja";
   $e->age  = 25;

   echo json_encode($e);

?>
Output:
{"name":"raja","age":25}

Likewise, if you need an array of Employee data, create an array and add more Emp object in to array. And print the array using json_encode. Here I put inside a loop to generate array of Employee data


<?php

class Emp {
      public $name = "";
      public $age  = 0;
      
   }

$stack = array();
for($i=0;$i<10;$i++)
{
    $e = new Emp();
   $e->name = "emp".$i;
   $e->age  = 25+$i;
    $stack[] = $e;

}
   echo json_encode($stack);

?>

Output:
[{"name":"emp0","age":25},{"name":"emp1","age":26},
{"name":"emp2","age":27},{"name":"emp3","age":28},
{"name":"emp4","age":29},{"name":"emp5","age":30},
{"name":"emp6","age":31},{"name":"emp7","age":32},
{"name":"emp8","age":33},{"name":"emp9","age":34}]

Here all the member variables are marked as public.Its more important here. If you mark your member variables other than public, you can not access them outside of your class and at the same time those variables, which are not marked as public, will not be displayed in the output.


<?php
class Emp {
      public $name = "";
      protected $age  = 0;
      
   }

    $emp = new Emp();
   $emp->name = "raja";
//   $emp->age  = 25; this line will throw error. because its marked as protected  

   echo json_encode($emp);

?>

Output:

{"name":"raja"}

  Reference: http://php.net/manual/en/ref.json.php