How to create a JSON object and send it as POST request using PHP
JavaScript Object Notation(JSON) is a lightweight human-readable text format for storing and transporting data consisting of name-value pairs and arrays.
It is commonly used in reading data from a web server, and displaying it on a web page.
JSON data can easily be sent between computers, applications, and can be used by any programming language. It is extensively used as the de-facto format for the data exchange in RESTful web services requests and responses. In fact, the success of RESTful web services can be attributed to the JSON format due to its ease of use on various platforms and languages.
JSON Syntax
Data in JSON objects is stored in name-value pairs, as in the example below:
From the above example, “firstName” is the name, and “John” is the value.
The name in the pair is always a string while its value can be of different data types which include: string, number, object, array, true, false, and null.
The name and value in a pair are separated by a colon (:).
The name-value pairs are separated by a comma (,).
The JSON object is enclosed in curly braces (<>). It can contain name-value pairs and/or arrays.
Arrays in JSON are enclosed square brackets ([]), and their values are separated by a comma (,).
Example
The above is an example of a JSON object containing data in name-value pairs. It has values of datatypes: string, number, object and array.
The value for the name «phoneNumbers» is an array of two objects.
The value for the name «address» is an object containing 3 name-value pairs.
The name «age» contains a value of type number.
How to create a JSON object in PHP
First is to create an array, then encode it into a JSON object.
Since data in JSON is stored in name-value pairs, we use the associative arrays which also store data in key-value pairs, where the key is used as an index to search the corresponding value in the array.
To create an associative array in PHP, we put our key-value pairs inside the array() function and use the double arrow operator (=>) to assign values to keys.
"John", "lastName" => "Doe", "email" => "johndoe@gmail.com", "phone" => "111-111-1111" );
After creating an associative array, then convert it into a JSON object using the PHP inbuilt json_encode() function as shown below.
Add a Content-Type header by adding header(«Content-Type:application/json») at the top of the PHP file for your output to be recognized as a JSON object.
"John", "lastName" => "Doe", "email" => "johndoe@gmail.com", "phone" => "111-111-1111" $jsonobject = json_encode($myobj); echo $jsonobject;
The above code will print out a JSON object as below:
How to create a JSON object with an array and nested object
To have a name with an object as its value, will just need to create an array and assign it to the key as the value while forming the associative array.
To have a name with an array value, we just need to create an array as the value, then create other arrays with key-value pairs inside it.
Example
"John", "lastName" => "Doe", "email" => "johndoe@gmail.com", "address" => array( "postalAddress" => "12345", "postalCode" => "5432", "city" => "Nairobi" ), "siblings" => array( array( "name" => "Joseph Doe" ), array( "name" => "Mary Doe" ) ) ); $jsonobject = json_encode($myarray); echo $jsonobject;
The above code will output a JSON object below:
Sending a JSON object as a post request in PHP
Now that you already know how to form a JSON object, let’s dive into how you can send it as POST request.
We will achieve that using PHP Curl as shown below:
"John", "lastName" => "Doe", "email" => "johndoe@gmail.com", "phone" => "111-111-1111" ); $url = "https://www.example.com/register" $payload = json_encode($myarray); $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $payload); curl_exec($curl); curl_close($curl);
Conclusion
In this tutorial we have covered what JSON is, why it’s important, how to create associative arrays in PHP, how to convert an associative array into a JSON object and how to send the created object in a POST request using PHP curl.
Related Articles
Php post input json
- Different ways to write a PHP code
- How to write comments in PHP ?
- Introduction to Codeignitor (PHP)
- How to echo HTML in PHP ?
- Error handling in PHP
- How to show All Errors in PHP ?
- How to Start and Stop a Timer in PHP ?
- How to create default function parameter in PHP?
- How to check if mod_rewrite is enabled in PHP ?
- Web Scraping in PHP Using Simple HTML DOM Parser
- How to pass form variables from one page to other page in PHP ?
- How to display logged in user information in PHP ?
- How to find out where a function is defined using PHP ?
- How to Get $_POST from multiple check-boxes ?
- How to Secure hash and salt for PHP passwords ?
- Program to Insert new item in array on any position in PHP
- PHP append one array to another
- How to delete an Element From an Array in PHP ?
- How to print all the values of an array in PHP ?
- How to perform Array Delete by Value Not Key in PHP ?
- Removing Array Element and Re-Indexing in PHP
- How to count all array elements in PHP ?
- How to insert an item at the beginning of an array in PHP ?
- PHP Check if two arrays contain same elements
- Merge two arrays keeping original keys in PHP
- PHP program to find the maximum and the minimum in array
- How to check a key exists in an array in PHP ?
- PHP | Second most frequent element in an array
- Sort array of objects by object fields in PHP
- PHP | Sort array of strings in natural and standard orders
- How to pass PHP Variables by reference ?
- How to format Phone Numbers in PHP ?
- How to use php serialize() and unserialize() Function
- Implementing callback in PHP
- PHP | Merging two or more arrays using array_merge()
- PHP program to print an arithmetic progression series using inbuilt functions
- How to prevent SQL Injection in PHP ?
- How to extract the user name from the email ID using PHP ?
- How to count rows in MySQL table in PHP ?
- How to parse a CSV File in PHP ?
- How to generate simple random password from a given string using PHP ?
- How to upload images in MySQL using PHP PDO ?
- How to check foreach Loop Key Value in PHP ?
- How to properly Format a Number With Leading Zeros in PHP ?
- How to get a File Extension in PHP ?
- How to get the current Date and Time in PHP ?
- PHP program to change date format
- How to convert DateTime to String using PHP ?
- How to get Time Difference in Minutes in PHP ?
- Return all dates between two dates in an array in PHP
- Sort an array of dates in PHP
- How to get the time of the last modification of the current page in PHP?
- How to convert a Date into Timestamp using PHP ?
- How to add 24 hours to a unix timestamp in php?
- Sort a multidimensional array by date element in PHP
- Convert timestamp to readable date/time in PHP
- PHP | Number of week days between two dates
- PHP | Converting string to Date and DateTime
- How to get last day of a month from date in PHP ?
- PHP | Change strings in an array to uppercase
- How to convert first character of all the words uppercase using PHP ?
- How to get the last character of a string in PHP ?
- How to convert uppercase string to lowercase using PHP ?
- How to extract Numbers From a String in PHP ?
- How to replace String in PHP ?
- How to Encrypt and Decrypt a PHP String ?
- How to display string values within a table using PHP ?
- How to write Multi-Line Strings in PHP ?
- How to check if a String Contains a Substring in PHP ?
- How to append a string in PHP ?
- How to remove white spaces only beginning/end of a string using PHP ?
- How to Remove Special Character from String in PHP ?
- How to create a string by joining the array elements using PHP ?
- How to prepend a string in PHP ?