Php получение post запроса json

JSON PHP

Обычно JSON используется для получения данных с сервера и вывода их на веб-странице.

В этой главе мы рассмотрим как обмениваться данными JSON между клиентом и сервером на PHP.

PHP файл

В PHP есть несколько встроенных функций для работы с данными JSON.

Объекты в PHP могут конвертироваться в JSON при помощи PHP функции json_encode():

 name = "John"; $myObj->age = 30; $myObj->city = "New York"; $myJSON = json_encode($myObj); echo $myJSON; ?> 

Клиентский JavaScript

К PHP файлу из предыдущего примера можно обратиться по AJAX запросу, используя на стороне клиента следующий JavaScript код. Функция JSON.parse() конвертирует полученные данные в JavaScript объект:

 var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() < if (this.readyState == 4 && this.status == 200) < var myObj = JSON.parse(this.responseText); document.getElementById("demo").innerHTML = myObj.name; >>; xmlhttp.open("GET", "demo_file.php", true); xmlhttp.send(); 

PHP массив

Массивы в PHP также конвертируются в JSON при помощи PHP функции json_encode():

Клиентский JavaScript

К PHP массиву из предыдущего примера также можно обратиться по AJAX запросу, используя на стороне клиента следующий JavaScript код. Функция JSON.parse() конвертирует полученные данные в JavaScript массив:

 var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() < if (this.readyState == 4 && this.status == 200) < var myObj = JSON.parse(this.responseText); document.getElementById("demo").innerHTML = myObj[2]; >>; xmlhttp.open("GET", "demo_file_array.php", true); xmlhttp.send(); 

PHP база данных

PHP — это серверный язык программирования и используется для операций, выполняемых только на стороне сервера, например, для доступа к базе данных.

Представьте, что у вас на сервере есть база данных, в которой содержится информация о товарах, покупателях и поставщиках. И вы хотите получить 10 первых записей в таблице покупателей («customers»).

Используем функцию JSON.stringify(), чтобы конвертировать JavaScript объект в JSON:

 obj = < "table":"customers", "limit":10 >; dbParam = JSON.stringify(obj); xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() < if (this.readyState == 4 && this.status == 200) < document.getElementById("demo").innerHTML = this.responseText; >>; xmlhttp.open("GET", "json_demo_db.php?x language-php"> query("SELECT name FROM ".$obj->table." LIMIT ".$obj->limit); $outp = array(); $outp = $result->fetch_all(MYSQLI_ASSOC); echo json_encode($outp); ?> 
  • Конвертируем данные запроса в объект при помощи PHP функции json_decode().
  • Обращаемся к базе данных и заполняем массив запрошенными данными.
  • Добавляем массив к объекту и возвращаем объект в виде строки JSON, используя функцию json_encode().

Обход полученных данных

Теперь конвертируем данные, полученные от PHP файла, в JavaScript объект или в данном случае в JavaScript массив. Для этого используем функцию JSON.parse():

 . xmlhttp.onreadystatechange = function() < if (this.readyState == 4 && this.status == 200) < myObj = JSON.parse(this.responseText); for (x in myObj) < txt += myObj[x].name + "
"; > document.getElementById("demo").innerHTML = txt; > >; .

PHP метод POST

При отправке данных на сервер лучше всего использовать метод POST.

Чтобы послать AJAX запрос, используя метод POST, следует задать нужный метод и откорректировать заголовок.

Данные, отправляемые на сервер, теперь должны быть аргументом в методе send():

 obj = < "table":"customers", "limit":10 >; dbParam = JSON.stringify(obj); xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() < if (this.readyState == 4 && this.status == 200) < myObj = JSON.parse(this.responseText); for (x in myObj) < txt += myObj[x].name + "
"; > document.getElementById("demo").innerHTML = txt; > >; xmlhttp.open("POST", "json_demo_db_post.php", true); xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlhttp.send("x language-php"> query("SELECT name FROM ".$obj->table." LIMIT ".$obj->limit); $outp = array(); $outp = $result->fetch_all(MYSQLI_ASSOC); echo json_encode($outp); ?>

Источник

Читайте также:  Html css online обучение

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.

Читайте также:  Php pack a string

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.

Источник

Receiving JSON POST data via PHP.

In a previous tutorial, I showed how to send JSON data via POST in PHP. This led to somebody asking me how to receive JSON POST data with PHP.

Читайте также:  Java combobox получить выбранное значение

To receive RAW post data in PHP, you can use the php://input stream like so:

//Receive the RAW post data via the php://input IO stream. $content = file_get_contents("php://input");

Now, let’s take a look at an example where we attempt to receive and validate JSON POST data:

 //Make sure that the content type of the POST request has been set to application/json $contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : ''; if(strcasecmp($contentType, 'application/json') != 0) < throw new Exception('Content type must be: application/json'); >//Receive the RAW post data. $content = trim(file_get_contents("php://input")); //Attempt to decode the incoming RAW post data from JSON. $decoded = json_decode($content, true); //If json_decode failed, the JSON is invalid. if(!is_array($decoded)) < throw new Exception('Received content contained invalid JSON!'); >//Process the JSON.

A drill-down of the code sample above:

  1. We validate the request type by checking to see if it is POST. This will prevent the script from trying to process other request types such as GET.
  2. We validate the content type. In this case, we want it to be application/json.
  3. We retrieve the raw POST data from the php://input stream.
  4. We attempt to decode the contents of the POST data from JSON into a PHP associative array.
  5. We check to see if the result is an array. If it is not an array, then something has gone wrong. To debug the issue even further, be sure to check out this article on JSON error handling in PHP.
  6. After that, we can process the associative array.

Hopefully, you found this tutorial to be helpful!

Источник

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:

Источник

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