- PHP JSON Parsing
- What is JSON
- Example
- Example
- Parsing JSON with PHP
- Encoding JSON Data in PHP
- Example
- Example
- Example
- Decoding JSON Data in PHP
- Example
- Example
- Example
- Example
- Extracting Values from Nested JSON Data in PHP
- Example
- doctor Brain
- json_decode
- Преобразование JSON в объект
- Преобразование JSON в ассоциативный массив
- Заключение
- Новые публикации
- JavaScript: сохраняем страницу в pdf
- HTML: Полезные примеры
- CSS: Ускоряем загрузку страницы
- JavaScript: 5 странностей
- JavaScript: конструктор сортировщиков
- Категории
- О нас
- Как прочитать JSON с помощью PHP
- Как прочитать содержимое файла
- Как получить значение через запятую в массиве данных файла JSON
- Ошибки при выводе JSON
- Читайте также
- Комментарии к статье “ Как прочитать JSON с помощью PHP ” (2)
PHP JSON Parsing
In this tutorial you will learn how to encode and decode JSON data in PHP.
What is JSON
JSON stands for JavaScript Object Notation. JSON is a standard lightweight data-interchange format which is quick and easy to parse and generate.
JSON, like XML, is a text-based format that’s easy to write and easy to understand for both humans and computers, but unlike XML, JSON data structures occupy less bandwidth than their XML versions. JSON is based on two basic structures:
- Object: This is defined as a collection of key/value pairs (i.e. key:value ). Each object begins with a left curly bracket < and ends with a right curly bracket >. Multiple key/value pairs are separated by a comma , .
- Array: This is defined as an ordered list of values. An array begins with a left bracket [ and ends with a right bracket ] . Values are separated by a comma , .
In JSON, keys are always strings, while the value can be a string , number , true or false , null or even an object or an array . Strings must be enclosed in double quotes » and can contain escape characters such as \n , \t and \ . A JSON object may look like this:
Example
Whereas an example of JSON array would look something like this:
Example
Tip: A data-interchange format is a text format which is used to interchange or exchange data between different platforms and operating systems. JSON is the most popular and lightweight data-interchange format for web applications.
Parsing JSON with PHP
JSON data structures are very similar to PHP arrays. PHP has built-in functions to encode and decode JSON data. These functions are json_encode() and json_decode() , respectively. Both functions only works with UTF-8 encoded string data.
Encoding JSON Data in PHP
In PHP the json_encode() function is used to encode a value to JSON format. The value being encoded can be any PHP data type except a resource, like a database or file handle. The below example demonstrates how to encode a PHP associative array into a JSON object:
Example
65, "Harry"=>80, "John"=>78, "Clark"=>90); echo json_encode($marks); ?>
The output of the above example will look like this:
Similarly, you can encode the PHP indexed array into a JSON array, like this:
Example
The output of the above example will look like this:
You can also force json_encode() function to return an PHP indexed array as JSON object by using the JSON_FORCE_OBJECT option, as shown in the example below:
Example
The output of the above example will look like this:
As you can see in the above examples a non-associative array can be encoded as array or object. However, an associative array always encoded as object.
Decoding JSON Data in PHP
Decoding JSON data is as simple as encoding it. You can use the PHP json_decode() function to convert the JSON encoded string into appropriate PHP data type. The following example demonstrates how to decode or convert a JSON object to PHP object.
Example
The output of the above example will look something like this:
By default the json_decode() function returns an object. However, you can optionally specify a second parameter $assoc which accepts a boolean value that when set as true JSON objects are decoded into associative arrays. It is false by default. Here’s an example:
Example
'; var_dump(json_decode($json, true)); ?>
The output of the above example will look something like this:
Now let’s check out an example that will show you how to decode the JSON data and access individual elements of the JSON object or array in PHP.
Example
'; // Decode JSON data to PHP associative array $arr = json_decode($json, true); // Access values from the associative array echo $arr["Peter"]; // Output: 65 echo $arr["Harry"]; // Output: 80 echo $arr["John"]; // Output: 78 echo $arr["Clark"]; // Output: 90 // Decode JSON data to PHP object $obj = json_decode($json); // Access values from the returned object echo $obj->Peter; // Output: 65 echo $obj->Harry; // Output: 80 echo $obj->John; // Output: 78 echo $obj->Clark; // Output: 90 ?>
You can also loop through the decoded data using foreach() loop, like this:
Example
'; // Decode JSON data to PHP associative array $arr = json_decode($json, true); // Loop through the associative array foreach($arr as $key=>$value)< echo $key . "=>" . $value . "
"; > echo "
"; // Decode JSON data to PHP object $obj = json_decode($json); // Loop through the object foreach($obj as $key=>$value)< echo $key . "=>" . $value . "
"; > ?>
Extracting Values from Nested JSON Data in PHP
JSON objects and arrays can also be nested. A JSON object can arbitrarily contains other JSON objects, arrays, nested arrays, arrays of JSON objects, and so on. The following example will show you how to decode a nested JSON object and print all its values in PHP.
Example
/* Loop through array, if value is itself an array recursively call the function else add the value found to the output items array, and increment counter by 1 for each value found */ foreach($arr as $key=>$value) < if(is_array($value))< printValues($value); >else < $values[] = $value; $count++; >> // Return total count and values found in array return array('total' => $count, 'values' => $values); > // Assign JSON encoded string to a PHP variable $json = ' < "book": < "name": "Harry Potter and the Goblet of Fire", "author": "J. K. Rowling", "year": 2000, "characters": ["Harry Potter", "Hermione Granger", "Ron Weasley"], "genre": "Fantasy Fiction", "price": < "paperback": "$10.40", "hardcover": "$20.32", "kindle": "4.11" >> >'; // Decode JSON data into PHP associative array format $arr = json_decode($json, true); // Call the function and print all the values $result = printValues($arr); echo "" . $result["total"] . " value(s) found:
"; echo implode("
", $result["values"]); echo "
"; // Print a single value echo $arr["book"]["author"] . "
"; // Output: J. K. Rowling echo $arr["book"]["characters"][0] . "
"; // Output: Harry Potter echo $arr["book"]["price"]["hardcover"]; // Output: $20.32 ?>
doctor Brain
Независимо от того, каким образом получены данные в формате JSON: в виде файла *.json переданного из стороннего API или входящей строки, нативный PHP, начиная с версии 5.2.0, предоставляет две замечательные функции json_encode и json_decode . Сегодня мы обратим внимание на функцию json_decode , которая позволяет преобразовать данные JSON в формат, пригодный для дальнейшей работы.
Итак, для начала нам нужны какие-то JSON-данные, и мы получим их, благодаря генератору случайных данных Mockaroo.
json_decode
Преобразование JSON в объект
Входящие JSON-данные всгеда являются строкой, как же их преобразовать? Посмотрим на код приведенный ниже:
$json = '[< "id": 1, "first_name": "Bertrando", "last_name": "Pedrollo", "email": "bpedrollo0@homestead.com", "gender": "Male", "ip_address": "62.137.20.86" >, < "id": 2, "first_name": "Pier", "last_name": "Winkworth", "email": "pwinkworth1@mit.edu", "gender": "Female", "ip_address": "158.139.30.200" >, < "id": 3, "first_name": "Joyous", "last_name": "Glascott", "email": "jglascott2@smh.com.au", "gender": "Female", "ip_address": "146.147.52.106" >, < "id": 4, "first_name": "Daniela", "last_name": "Hawes", "email": "dhawes3@timesonline.co.uk", "gender": "Female", "ip_address": "148.153.203.134" >]'; $decodedJson = json_decode($json); var_dump($decodedJson);
После преобразования JSON-данных с помощью функции json_decode , мы вывели их на странцу. Можно увидеть, что полученный результат — массив объектов (stdClass):
array(4) < [0]=>object(stdClass)#1 (6) < ["id"]=>int(1) ["first_name"]=> string(9) "Bertrando" ["last_name"]=> string(8) "Pedrollo" ["email"]=> string(24) "bpedrollo0@homestead.com" ["gender"]=> string(4) "Male" ["ip_address"]=> string(12) "62.137.20.86" > [1]=> object(stdClass)#2 (6) < ["id"]=>int(2) ["first_name"]=> string(4) "Pier" ["last_name"]=> string(9) "Winkworth" ["email"]=> string(19) "pwinkworth1@mit.edu" ["gender"]=> string(6) "Female" ["ip_address"]=> string(14) "158.139.30.200" > [2]=> object(stdClass)#3 (6) < ["id"]=>int(3) ["first_name"]=> string(6) "Joyous" ["last_name"]=> string(8) "Glascott" ["email"]=> string(21) "jglascott2@smh.com.au" ["gender"]=> string(6) "Female" ["ip_address"]=> string(14) "146.147.52.106" > [3]=> object(stdClass)#4 (6) < ["id"]=>int(4) ["first_name"]=> string(7) "Daniela" ["last_name"]=> string(5) "Hawes" ["email"]=> string(25) "dhawes3@timesonline.co.uk" ["gender"]=> string(6) "Female" ["ip_address"]=> string(15) "148.153.203.134" > >
Теперь мы можем получить нужные данные из переменной decodedJson, использую синтаксис для работы с объектами:
echo $decodedJson[0]->first_name . " " . $decodedJson[0]->last_name; echo "
"; echo $decodedJson[1]->first_name . " " . $decodedJson[1]->last_name; // Результат: // Bertrando Pedrollo // Pier Winkworth
Преобразование JSON в ассоциативный массив
Для того, чтобы результатом преобразования JSON-данных с помощью функции jsin_decode стал ассоциативный массив, а не объект (stdClass), нужно добавить второй параметр $assoc равный true (по умолчанию его значение — false).
$json = '[< "id": 1, "first_name": "Bertrando", "last_name": "Pedrollo", "email": "bpedrollo0@homestead.com", "gender": "Male", "ip_address": "62.137.20.86" >, < "id": 2, "first_name": "Pier", "last_name": "Winkworth", "email": "pwinkworth1@mit.edu", "gender": "Female", "ip_address": "158.139.30.200" >, < "id": 3, "first_name": "Joyous", "last_name": "Glascott", "email": "jglascott2@smh.com.au", "gender": "Female", "ip_address": "146.147.52.106" >, < "id": 4, "first_name": "Daniela", "last_name": "Hawes", "email": "dhawes3@timesonline.co.uk", "gender": "Female", "ip_address": "148.153.203.134" >]'; $decodedJson = json_decode($json, true); var_dump($decodedJson);
array(4) < [0]=>array(6) < ["id"]=>int(1) ["first_name"]=> string(9) "Bertrando" ["last_name"]=> string(8) "Pedrollo" ["email"]=> string(24) "bpedrollo0@homestead.com" ["gender"]=> string(4) "Male" ["ip_address"]=> string(12) "62.137.20.86" > [1]=> array(6) < ["id"]=>int(2) ["first_name"]=> string(4) "Pier" ["last_name"]=> string(9) "Winkworth" ["email"]=> string(19) "pwinkworth1@mit.edu" ["gender"]=> string(6) "Female" ["ip_address"]=> string(14) "158.139.30.200" > [2]=> array(6) < ["id"]=>int(3) ["first_name"]=> string(6) "Joyous" ["last_name"]=> string(8) "Glascott" ["email"]=> string(21) "jglascott2@smh.com.au" ["gender"]=> string(6) "Female" ["ip_address"]=> string(14) "146.147.52.106" > [3]=> array(6) < ["id"]=>int(4) ["first_name"]=> string(7) "Daniela" ["last_name"]=> string(5) "Hawes" ["email"]=> string(25) "dhawes3@timesonline.co.uk" ["gender"]=> string(6) "Female" ["ip_address"]=> string(15) "148.153.203.134" > >
Теперь, для того чтобы получить необходимые данные, нужно использовать синтаксис для работы с массивами:
echo $decodedJson[0]["first_name"] . " " . $decodedJson[0]["last_name"]; echo "
"; echo $decodedJson[1]["first_name"] . " " . $decodedJson[1]["last_name"]; // Результат: // Bertrando Pedrollo // Pier Winkworth
Заключение
Примеры, разбираемые в данной статье, в очередной раз демонстрируют наличие в PHP великолепных нативных функций и замечательной документации. Не поленитесь изучить дополнительную информацию о json_decode на официальном сайте.
Новые публикации
JavaScript: сохраняем страницу в pdf
HTML: Полезные примеры
CSS: Ускоряем загрузку страницы
JavaScript: 5 странностей
JavaScript: конструктор сортировщиков
Категории
О нас
Frontend & Backend. Статьи, обзоры, заметки, код, уроки.
© 2021 dr.Brain .
мир глазами веб-разработчика
Как прочитать 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, то вам отдельно придется её гуглить. На сайте кажется я её ещё не описывал.