How to get json data in php

Работа с JSON в PHP

JSON (JavaScript Object Notation) – текстовый формат обмена данными, основанный на JavaScript, который представляет собой набор пар . Значение может быть массивом, числом, строкой и булевым значением.

В PHP поддержка JSON появилась с версии 5.2.0 и работает только с кодировкой UTF-8.

Кодирование

json_encode($value, $options) – кодирует массив или объект в JSON.

$array = array( '1' => 'Значение 1', '2' => 'Значение 2', '3' => 'Значение 3', '4' => 'Значение 4', '5' => 'Значение 5' ); $json = json_encode($array); echo $json;

Как видно кириллица кодируется, исправляется это добавлением опции JSON_UNESCAPED_UNICODE .

$json = json_encode($array, JSON_UNESCAPED_UNICODE); echo $json;

Далее такую строку можно сохранить в файл, или отдать в браузер, например при AJAX запросах.

header('Content-Type: application/json'); echo $json; exit();

Декодирование

Функция json_decode($json) преобразует строку в объект:

$json = ''; $array = json_decode($json); print_r($array);
stdClass Object ( [1] => Значение 1 [2] => Значение 2 [3] => Значение 3 [4] => Значение 4 [5] => Значение 5 )

Если добавить вторым аргументом true , то произойдёт преобразование в массив:

$json = ''; $array = json_decode($json, true); print_r($array);
Array ( [1] => Значение 1 [2] => Значение 2 [3] => Значение 3 [4] => Значение 4 [5] => Значение 5 )

Получение ошибок и их исправление

json_decode() возвращает NULL , если в объекте есть ошибки, посмотреть их можно с помощью функции json_last_error() :

$json = ''; $array = json_decode($json, true); switch (json_last_error())

Посмотреть значения констант JSON:

$constants = get_defined_constants(true); foreach ($constants['json'] as $name => $value) < echo $name . ': ' . $value . '
'; >
JSON_HEX_TAG: 1 JSON_HEX_AMP: 2 JSON_HEX_APOS: 4 JSON_HEX_QUOT: 8 JSON_FORCE_OBJECT: 16 JSON_NUMERIC_CHECK: 32 JSON_UNESCAPED_SLASHES: 64 JSON_PRETTY_PRINT: 128 JSON_UNESCAPED_UNICODE: 256 JSON_PARTIAL_OUTPUT_ON_ERROR: 512 JSON_PRESERVE_ZERO_FRACTION: 1024 JSON_UNESCAPED_LINE_TERMINATORS: 2048 JSON_OBJECT_AS_ARRAY: 1 JSON_BIGINT_AS_STRING: 2 JSON_ERROR_NONE: 0 JSON_ERROR_DEPTH: 1 JSON_ERROR_STATE_MISMATCH: 2 JSON_ERROR_CTRL_CHAR: 3 JSON_ERROR_SYNTAX: 4 JSON_ERROR_UTF8: 5 JSON_ERROR_RECURSION: 6 JSON_ERROR_INF_OR_NAN: 7 JSON_ERROR_UNSUPPORTED_TYPE: 8 JSON_ERROR_INVALID_PROPERTY_NAME: 9 JSON_ERROR_UTF16: 10

Если вы хотите распарсить JS объект из HTML страницы или файла, то скорее всего json_decode вернет ошибку т.к. в коде будут управляющие символы или BOM. Удалить их можно следующим образом:

$json = ''; // Удаление управляющих символов for ($i = 0; $i // Удаление символа Delete $json = str_replace(chr(127), '', $json); // Удаление BOM if (0 === strpos(bin2hex($json), 'efbbbf')) < $json = substr($json, 3); >$res = json_decode($json, true); print_r($res);

HTTP-запросы в формате JSON

Некоторые сервисы требуют чтобы запросы к ним осуществлялись в формате JSON, такой запрос можно сформировать в CURL:

$data = array( 'name' => 'snipp.ru' 'text' => 'Отправка сообщения', ); $ch = curl_init('https://example.com'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); $res = curl_exec($ch); curl_close($ch);

А также могут обратится к вашим скриптам в таком формате, чтение JSON запроса.

$data = file_get_contents('php://input'); $data = json_decode($data, true);

Источник

Читайте также:  Creating menu in html and css

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» >

Читайте также:  Sending email php using smtp

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.

Читайте также:  Изменение css при уменьшении экрана

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 Parse JSON in PHP

Monty Shokeen

Monty Shokeen Last updated May 31, 2021

JSON, short for JavaScript Object Notation, is a common lightweight format for storing and exchanging information. As the name suggests, it was initially derived from JavaScript, but it is a language-independent format for storing information. A lot of languages like PHP now implement functions to read and create JSON data.

This tutorial will teach you how to read a JSON file and convert it to an array in PHP. Learn how to parse JSON using the json_decode() and json_encode() functions.

Reading JSON From a File or String in PHP

Let’s say you have a file which contains information in JSON format. How do you access and store it in PHP?

First, you need to get the data from the file into a variable by using file_get_contents() . Once the data is in a string, you can call the json_decode() function to extract information from the string. Keep in mind that JSON simply provides a way to store information as a string using a set of predefined rules. It is our job to decode the strings properly and get the information we want.

The json_decode() function accepts four parameters, but you will only need the first two in most situations. The first parameter specifies the string that you want to decode. The second parameter determines how the decoded data is returned. Setting it to true will return an associative array, and false will return objects. Here is a basic example. We have a file called people.json with the following contents:

Источник

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