Array to JSON conversion in PHP using json_encode

If you are reading this article, then most probably you already know about JSON and PHP array. Now I am going to show you how you can convert any PHP array into JSON formatted string. So keep reading to learn the task.

PHP already has an inbuilt function which is json_encode. Using the json_encode() PHP function we can easily convert an array into a JSON string data. Using this function, we can do the task quite easily. All you need to do is just pass the array as the parameter to the json_encode() function. Below is the simple syntax of it:

json_encode( ARRAY )

Now it is time to see the code. Below is the given PHP code snippet which shows how we can do it easily:

<?php
// Create our array
$arr = array(
  "color"=>"red",
  "height"=>67,
  "place"=>array(
     "city"=>"Kolkata",
     "country"=>"India",
  ),
);

// Get JSON from array
$json_data = json_encode($arr);

?>

In the above code, we have first declared our array in PHP and store it in the variable. After that, we pass it to the json_encode function.

That’s it…

Now if we print it using the inbuilt print function:

print($json_data);

If we run our code, we will see the JSON formatted string as a result on the page as you can see below:

{
   "color":"red",
   "height":67,
   "place":{
      "city":"Kolkata",
      "country":"India"
   }
}

So you can see that we have successfully able to do our task. As you have seen that the main functionality is done just one line of code:

$json_data = json_encode($arr);

I hope, this tutorial will be going to help you with your project.

Also, read: Conversion of JSON string to PHP Array

Leave a Reply

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