- Catch and parse JSON Post data in PHP
- How to extract and access JSON data in PHP
- How to receive JSON data in PHP
- 1. From a POST or GET request
- 2. Reading a JSON file
- Extracting/Decoding JSON data in PHP
- 1. Accessing JSON data as a PHP object
- 2. Accessing JSON data as an array
- 3. Accessing data in a nested JSON object
- Looping through an object of objects with foreach()
- Conclusion
- Related Articles
- Sending JSON to REST API Endpoint [PHP Code]
- PHP code for REST API POST Example
- What is JSON?
- What is HTTP POST?
- What is REST API?
- PHP REST API POST Example
- What is the correct content type when posting JSON to a REST API endpoint?
- Why is it important to specify the correct Content-Type when posting JSON to a REST API endpoint?
- See also
- Generate code snippets for PHP and other programming languages
Catch and parse JSON Post data in PHP
A few days ago I’ve been working a project which, as many other projects out there today, communicates with some external APIs. At some point, in order to perform some tests, I had to write an API endpoint within my project itself to fake the actual external API. I need to mention that the external API was expecting application/json content type, so basically the curl setup looked like this:
timeout_limit ); curl_setopt( $ch, CURLOPT_ENCODING, '' ); curl_setopt( $ch, CURLOPT_MAXREDIRS, 10 ); curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, 'POST' ); curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $data ) ); curl_setopt( $ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json' ) ); // .
The issue was that when I’ve been trying to catch the POST data and use it, I was getting null as a value for both $_POST or $_REQUEST , and I couldn’t understand why 🤔. Apparently (and maybe many of you already knew that), if the data is sent as multipart/form-data or application/x-www-form-urlencoded then yes, you can use PHP globals $_POST or $_REQUEST to catch and use that data. But, if the data is sent as application/json , then prior to PHP 5.6 you could’ve use $HTTP_RAW_POST_DATA to grab the raw POST data, or (and based on PHP docs this is the preferable way to do it) use the php://input — a read-only stream that allows you to read raw data from the request body. So, as a result I ended up grabbing the POST data like this:
How to extract and access JSON data in 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 easy to generate and parse in many programming languages. It is the most popular and lightweight data-interchange format for web applications and the de-facto format for the data exchange in RESTful web services requests and responses.
In this post, we will cover how to decode a JSON object and access its data in PHP.
Below is an example of a simple JSON object:
How to receive JSON data in PHP
1. From a POST or GET request
To receive JSON data as a POST request, we use the “php://input” along with the function file_get_contents() as below:
For instance, the JSON data is sent below as a POST request:
'; $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);
To receive the above request data in the register.php file, just add file_get_contents(«php://input») and assign it to a variable for processing eg:
2. Reading a JSON file
A JSON file contains a JSON object and has a file extension of .json. You can as well open the file in PHP and access its data.
Similar to POST or GET request, we use file_get_contents() but instead of having “php://input”, we use the file path.
For example, if we have a JSON file with path «https://www.example.com/mydata.json«, we can access its data as below:
If the json file and the PHP file accessing it are in the same website, we can use relative path instead of the full file URL.
Extracting/Decoding JSON data in PHP
We use the built-in function json_decode() to convert the JSON string to the appropriate data type such as an object or an array.
1. Accessing JSON data as a PHP object
By default the json_decode() function returns an object.
Example
The example below decodes a JSON object into a PHP object:
'; $data = json_decode($json); var_dump($data);
The above example outputs below:
object(stdClass)#1 (4) < ["firstName"]=>string(4) «John» [«lastName»]=> string(3) «Doe» [«email»]=> string(17) «johndoe@gmail.com» [«phone»]=> string(12) «111-111-1111» >
To access the PHP object data, you use the object operator (->) after the object name, followed by the key of the key-value pair. This is the same as the name in the name-value pair in JSON object eg $data->firstName .
'; $data = json_decode($json); echo "My name is".$data->firstName." ".$data->lastName; //Output: My name is John Doe
2. Accessing JSON data as an array
You can as well convert the JSON object to a PHP associative array by passing a second(optional) parameter in the json_decode() function with the boolean value «true» as below. The value is set to false by default if you don’t pass it.
The example below decodes JSON object into a PHP associative array:
'; $data = json_decode($json, true); var_dump($data);
The above example outputs below:
array(4) < ["firstName"]=>string(4) «John» [«lastName»]=> string(3) «Doe» [«email»]=> string(17) «johndoe@gmail.com» [«phone»]=> string(12) «111-111-1111» >
You access the data as in any other PHP associative array as in the example below:
'; $data = json_decode($json, true); echo "My name is ".$data["firstName"]." ".$data["lastName"]; //Output: My name is John Doe
3. Accessing data in a nested JSON object
A JSON object may comprise of json objects and arrays as the values in its name-value pairs such as in the example below:
In the above example, the «address» has an object as its value while «siblings» has an array value comprising of objects.
The easiest way of accessing all the data is decoding the object as an associative array.
, "siblings": [ < "name": "Joseph Doe" >, < "name": "Mary Doe" >] >'; $data = json_decode($json, true); //Displaying all the data echo "First Name: ".$data["firstName"]."
"; //Output -> First Name: John echo "First Name: ".$data["lastName"]."
"; //Output -> Last Name: Doe echo "Email Address: ".$data["email"]."
"; //Output -> Email Address: johndoe@gmail.com echo "Postal Address: ".$data["address"]["postalAddress"]."
"; //Output -> Postal Address: 12345 echo "Postal Code: ".$data["address"]["postalCode"]."
"; //Output -> Postal Code: 5432 echo "City: ".$data["address"]["city"]."
"; //Output -> City: Nairobi echo "Sibling 1: ".$data["siblings"][0]["name"]."
"; //Output -> Sibling 1: Joseph Doe echo "Sibling 2: ".$data["siblings"][1]["name"]."
"; //Output -> Sibling 2: Mary Doe
Looping through an object of objects with foreach()
You may have a large JSON object made of an array of objects, like in the example below:
To access the values of a country in the example above, you just have to know its object position in the array. For example, china is in the third position. But when accessing the array items, we start counting from 0, hence the index of China in the array is 2.
We access the China array object as below:
"; //Output -> Country: China echo "Code: ".$data["countries"][2]["code"]."
"; //Output -> Code: CN echo "City: ".$data["countries"][2]["city"]."
"; //Output -> City: Beijing
If you want to access all the array data then it can be tiresome and time-consuming to write the code for accessing each at a time especially when the object is large. For such an instance, you can use the foreach() function to loop through all the objects as below:
, < "name": "India", "code": "IN", "city": "New Delhi" >, < "name": "China", "code": "CN", "city": "Beijing" >, < "name": "Germany", "code": "DE", "city": "Berlin" >, < "name": "Kenya", "code": "KE", "city": "Nairobi" >] >'; $countries = json_decode($json)->countries; foreach($countries as $country)< echo "Country: ".$country->name."
"; echo "Code: ".$country->code."
"; echo "City: ".$country->city."
"; >
Conclusion
In this post, we have covered everything you need to know in extracting and accessing a JSON object data using PHP.
If you want to get notified via email when we add more incredible content to our blog, kindly subscribe to our email newsletter.
Related Articles
Sending JSON to REST API Endpoint [PHP Code]
To post JSON to a REST API endpoint using PHP, you must send an HTTP POST request to the REST API server and provide JSON data in the body of the PHP POST message. You must also specify the data type using the Content-Type: application/json request header. In this PHP REST API POST example, we also send the Accept: application/json request header to tell the REST API server that the PHP API client expects JSON in response. The PHP code was automatically generated for the REST API POST example.
POST /echo/post/json HTTP/1.1 Host: reqbin.com Accept: application/json Content-Type: application/json Content-Length: 81
PHP code for REST API POST Example
This PHP code snippet was generated automatically for the REST API POST example.
What is JSON?
JavaScript Object Notation is a data interchange format that specifies formatting rules for the portable representation of structured data. JSON represents four primitive types (strings, numbers, booleans, and null) and two structured types (objects and arrays).
What is HTTP POST?
HTTP POST is one of the nine standard HTTP methods. The POST method requests that the REST API server accept the object enclosed in the body of the message at the endpoint identified by the Request-URI. The POST method differs from HTTP HEAD and GET requests in that HTTP POST requests can change the server’s state.
What is REST API?
REST stands for Representative State Transfer and is a way of connecting two computer systems over the Internet. The REST API is a browser and programming language agnostic. You can run your REST API client in any modern browser or create a desktop or mobile REST API application using any programming language, including PHP.
- Client-server: the REST API client user interface (website, desktop or mobile application) should be decoupled from the REST API server (request processor and data storage) so that each part can be developed and scaled individually.
- Stateless: Every REST API request must be executed with all the necessary data, without assuming that the server might have any data from previous REST API client requests.
- Layered: the REST API client does not need to know if it communicates with an actual server or an intermediary. Intermediate servers (proxies or load balancers) can provide the underlying REST API server with additional scalability and security.
- Cacheable: each REST API response must be defined as cacheable or not.
PHP REST API POST Example
To send data to the REST API server using PHP, you must make an HTTP POST request and include the POST data in the request’s body. You also need to provide the Content-Type: application/json and Content-Length request headers. Below is an example of a REST API POST request to a ReqBin API endpoint. Click on Generate Code to see the PHP code for this REST API POST example.
POST /echo/post/json HTTP/1.1 Host: reqbin.com Accept: application/json Content-Type: application/json Content-Length: 81
In this REST API POST request example, the server informs the REST API client that it has returned JSON by sending Content-Type: application/json header in response.
Server response to our test REST API POST request.
HTTP/1.1 200 OK Content-Type: application/json Content-Length: 19
What is the correct content type when posting JSON to a REST API endpoint?
The official MIME type for JSON is application/json. To POST JSON data to the server, you must specify the data type in the body of the POST message using the appropriate Content-Type request header.
Content-Type: application/json
Why is it important to specify the correct Content-Type when posting JSON to a REST API endpoint?
If you don’t pass the correct Content-Type header to the server, your application may not work. The REST API server needs a valid Content-Type header to interpret the request message body data correctly. This is especially important for MVC frameworks that implicitly convert values from JSON to local variables.
If your PHP REST API client expects JSON data from the server, it must also send the Accept: application/json request header. The Accept header tells the server that the client can accept and process JSON data. If the server returns data in JSON format, it must inform the PHP API client of the data type using the Content-Type: application/json response header.
See also
Generate code snippets for PHP and other programming languages
Convert your REST API POST request to the PHP, JavaScript/AJAX, Node.js, Curl/Bash, Python, Java, C#/.NET code snippets using the PHP code generator.