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:
- Convert Associative Array into XML in PHP
- Convert XML into Associative Array in PHP
- Converting JSON to Array or Object in PHP
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:
- Working with php.ini file Configuration
- Control Statements in PHP
- Convert Associative Array into XML in PHP
- Convert XML into Associative Array in PHP
- Using Prepared Statement with PHP & MySQL
- How to Upload File in PHP
- Converting JSON to Array or Object in PHP
- Manipulating PHP arrays: push, pop, shift, unshift
- Remove Repeated Words From String in PHP
- Converting a PHP Array to a Query String
- 15+ regular expressions for PHP developers
- 10 Most Important Directory Functions in PHP
- 10 little known but useful PHP functions
- PHP Script to Download Large Files Reliably