Php пост запрос json

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:

Читайте также:  Send function in python

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.

Источник

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.

Источник

Оцените статью