Open In App

Which functions are used to encode and decode JSON file in PHP ?

Last Updated : 06 Dec, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

JSON stands for JavaScript Object Notation. Like XML, it is a text-based format for the exchange of data which is easier to read and write and it is lighter than other formats. JSON is based on two basic structures namely Objects and Arrays. 

Parsing JSON data in PHP: There are built-in functions in PHP for both encoding and decoding JSON data. These functions are json_encode() and json_decode(). These functions works only with UTF-8 encoded string.

Decoding JSON data in PHP: It is very easy to decode JSON data in PHP. You just have to use json_decode() function to convert JSON objects to the appropriate PHP data type.

Example: By default the json_decode() function returns an object. You can optionally specify a second parameter that accepts a boolean value. When it is set as “true”, JSON objects are decoded into associative arrays.

PHP




<?php
    $student_data = '{"Ram":96,"Prashant":76,"Varun":65,"Mark":34}';
  
    // Decoding above JSON String into JSON object
    $decoded = json_decode($student_data);
      
    // Dump the $decoded variable
    var_dump($decoded);
?>


Output:  

Encoding JSON data in PHP: Encoding JSON data is as easy as encoding JSON data in PHP. We use the json_encode() function, the data being encoded can be any PHP data type except a resource like a filehandle.

Example 1: The following code demonstrates encoding PHP associative array.

PHP




<?php
  
    // PHP associative array
    $student_data = array(
        "Ram"=>96, 
        "Prashant"=>76, 
        "Varun"=>65, 
        "Mark"=>34
    );
  
    // Encoding PHP Associative array using json_encode()
    $encoded = json_encode($student_data);
  
   // Echo the data
    echo $encoded;
?>


Output:

{"Ram":96,"Prashant":76,"Varun":65,"Mark":34} 

Example 2: The following code demonstrates encoding PHP indexed array.

PHP




<?php
  
   // PHP associative array
   $students = array("Ram", "Prashant", "Varun", "Mark");
  
   // Encoding PHP Associative array using json_encode()
   $encoded = json_encode($students);
  
   // Echo the data
   echo $encoded;
?>


Output:

["Ram","Prashant","Varun","Mark"]


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads