Json - With PHP

Json - With PHP

  • JSON is included in PHP 5.2.0 version.
  • json_encode() method takes as input, a PHP variable and, outputs a JSON string equivalent to that variable. 
  • json_decode() method, does the reverse process by decoding a JSON variable. 
  • json_last_error() method displays the recent error data.

Sample Code :

    $WikiTechy_employees =  
        '{"firstName":"jln","lastName":"jayaka" }';     
    echo json_encode( $WikiTechy_employees);

Code Path :

  • Type the above code in an editor such as notepad and save it with “.php” file extension in the following path as shown below:

Pre-requisite :

  • Start the apache server through XAMPP as follows

    The element <?phpwill indicates the browser that it is a PHP code.

    A variable $WikiTechy_employeesis declared with a firstname and lastname attributes as follows: 

         $WikiTechy_employees =  

         '{"firstName":"jln","lastName":"jayaka" }';    

    The code echo json_encode( $WikiTechy_employees)  ; displays the value of variable $WikiTechy_employeesin browser.

    Finally, PHP code’s ending element is shown by “?>”.

Execution :

  • Go to browser and type http://localhost:85/json_wikiTechy/10.json-with-php.php to execute the above code.

Note :

1.The path json_wikiTechy/10.json-with-php.php indicates the file path as shown in fig1. Use your machine path here

2.Check for the XAMPP’s localhost port number in Apache Config file as shown below and use the appropriate port number for executing your php code.

Output :