Php get json format

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:

Читайте также:  Birthday Reminders for August

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.

Источник

Работа с 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);

Источник

Как прочитать JSON с помощью PHP

Admin 05.11.2017 , обновлено: 21.12.2017 PHP, WordPress

Формат JSON представляет из себя упорядоченную, определенным образом, информацию. Это альтернатива формату XML, с более минималистической структурой данных. О том, как прочитать эти данные через PHP.

JSON можно прочитать с помощью очень многих языков программирования. Здесь мы будем разбирать пример чтения содержимого файла посредством PHP.

Как прочитать содержимое файла

В переменную f_json заключаем адрес файла JSON:

Затем этот файл достаём по адресу указанному в f_json:

Если заглянуть в JSON файл напрямую, можно увидеть следующие данные:

Иногда в файле данные выглядят так:

Эта «неправильная» кодировка является символами Unicode, записанные в восьмибитной кодировке.

Просмотрим содержимое файла JSON в браузере:

В данном случае будет отдан массив в одну строчку. Ниже строчка разбита, для наглядности, на несколько строк.

object(stdClass)#3896 (1)
< ["response"]=>object(stdClass)#3324 (1)
< ["items"]=>array(1) < [0]=>object(stdClass)#3330 (5)
< ["id"]=>string(4) «1331»
[«title_one»]=> string(40) «Данные заголовка один»
[«title_two»]=> string(38) «Данные заголовка два»
[«Год»]=> string(4) «2056»
[«Items»]=> string(34) «items-1, items-2, items-3, items-4»
> > > >

Для чтения этих данных декодируем строки файла:

Теперь выведем объекты в этом файле. Например, мы хотим достать заголовок один, который находится под ключевым атрибутом title_one. Для этого воспользуемся следующей командой:

Мы сохранили данные в переменную title_one. Теперь с ними можно делать всё что угодно. Например, вывести её:

В этом случае будет показано:

Как получить значение через запятую в массиве данных файла JSON

Пример посложнее. Мы хотим достать отдельные данные для «items-1, items-2, items-3, items-4». Чтобы каждое значение было схвачено в отдельную переменную.

Для этого, сначала мы обратимся к этой строке:

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

Теперь мы можем вывести отдельные элементы так:

Причем первое значение выводится с параметром [0]. Так исторически сложилось.

Ошибки при выводе JSON

Если вы сталкиваетесь с командой вроде:

Значит неправильно указан путь к данным.

Читайте также

У сайта нет цели самоокупаться, поэтому на сайте нет рекламы. Но если вам пригодилась информация, можете лайкнуть страницу, оставить комментарий или отправить мне подарок на чашечку кофе.

Комментарии к статье “ Как прочитать JSON с помощью PHP ” (2)

Привет ! подскажи пожалуйста, есть такая задача, скачать и разобрать данные в виде JSON при помощи PHP. Сгенерировать в html страницу , есть ссылка откуда брать json, как это вообще сделать ?? Готовая программа должна скачивать эти данные с файла c помощью ajax

В статье расписано, как разбирать данные json на php. Прочитайте статью и попробуйте сделать что в ней указано. Что касается технологии ajax, то вам отдельно придется её гуглить. На сайте кажется я её ещё не описывал.

Источник

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