Converting an Array to JSON in PHP

In our previous tutorial, we have explained how to convert associative array into XML in PHP. In this tutorial we will explain how to convert an array to JSON object in PHP.

JSON is stands for JavaScript Object Notation. Currently, JSON is the most used data format to handle data. The major use of JSON is to fetch and return data in JSON format from server and to use the JSON data at client end.

While developing APIs, data is accessed from database and converted to JSON data to return response in JSON format. In PHP, we can easily convert an array to JSON with json_encode() function. For example, if we get data from database or have data in associative array with key value. Then we can easily convert this array to JSON object using PHP.

Also, read:

Here is the data in associative array with key value:


<?php

$empData = array (       
    
    array( 
        "name" => "Jhon Smith", 
        "age" => "40"
    ), 
    array( 
        "name" => "Kane William", 
        "age" => "50"
    ), 
    array( 
        "name" => "Ian David", 
        "age" => "30"
    ) 
); 
  
echo json_encode($empData); 

?>

We will run above code, it will convert the $empData array into JSON data using json_encode() function.

Below is the JSON output from above code example.

[{"name":"Jhon Smith","age":"40"},
{"name":"Kane William","age":"50"},
{"name":"Ian David","age":"30"}]

You may also like:

Leave a Reply

Your email address will not be published. Required fields are marked *