Работа с 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);
PHP JSON
Summary: in this tutorial, you will learn how to convert data in PHP to JSON data and vice versa using the PHP JSON extension.
JSON stands for JavaScript Object Notation. JSON is designed as a lightweight data-interchange format.
JSON is built on two structures:
- A collection of name/value pairs called JSON objects. JSON objects are equivalent to associative arrays in PHP.
- An ordered list of values called arrays. They’re equivalent to indexed arrays in PHP.
The JSON format is human-readable and easy for computers to parse. Even though JSON syntax derives from JavaScript, it’s designed to be language-independent.
PHP JSON extension
PHP natively supports JSON via the JSON extension. The JSON extension provides you with some handy functions that convert data from PHP to JSON format and vice versa.
Since the JSON extension comes with PHP installation by default, you don’t need to do any extra configuration to make it works.
Converting PHP variables to JSON using json_encode() function
To get a JSON representation of a variable, you use the json_encode() function:
json_encode ( mixed $value , int $flags = 0 , int $depth = 512 ) : string|false
Code language: PHP (php)
The following example uses the json_encode() function to convert an indexed array in PHP to JSON format:
$names = ['Alice', 'Bob', 'John']; $json_data = json_encode($names); // return JSON to the browsers header('Content-type:application/json'); echo $json_data;
Code language: PHP (php)
- First, define an array of strings that consists of three elements.
- Second, convert the array to JSON using the json_encode() function.
- Third, return the JSON data to the browsers by setting the content type of the document to appplication/json using the header() function.
[ "Alice", "Bob", "John" ]
Code language: JSON / JSON with Comments (json)
The following example uses the json_encode() function to convert an associative array in PHP to an object in JSON:
$person = [ 'name' => 'Alice', 'age' => 20 ]; header('Content-type:application/json'); echo json_encode($person);
Code language: PHP (php)
< name: "Alice", age: 20 >
Code language: PHP (php)
In practice, you would select data from a database and use the json_encode() function to convert it to the JSON data.
Converting JSON data to PHP variables
To convert JSON data to a variable in PHP, you use the json_decode() function:
json_decode ( string $json , bool|null $associative = null , int $depth = 512 , int $flags = 0 ) : mixed
Code language: PHP (php)
The following example shows how to use json_decode() function to convert JSON data to a variable in PHP:
$json_data = ''; $person = json_decode($json_data); var_dump($person);
Code language: PHP (php)
object(stdClass)#1 (2) ["name"] => string(5) "Alice" ["age"] => int(20) >
Code language: PHP (php)
In this example, the json_decode() function converts an object in JSON to an object in PHP. The object is an instance of the stdClass class. To convert JSON data to an object of a specific class, you need to manually map the JSON key/value pairs to object properties. Or you can use a third-party package.
Serializing PHP objects
To serialize an object to JSON data, you need to implement the JsonSerializable interface. The JsonSerializable interface has the jsonSerialize() method that specifies the JSON representation of the object.
For example, the following shows how to implement the JsonSerializable interface and use the json_encode() function to serialize the object:
class Person implements JsonSerializable < private $name; private $age; public function __construct(string $name, int $age) < $this->name = $name; $this->age = $age; > public function jsonSerialize() < return [ 'name' => $this->name, 'age' => $this->age ]; > > // serialize object to json $alice = new Person('Alice', 20); echo json_encode($alice);
Code language: PHP (php)
"name"
:"Alice","age":20>Code language: PHP (php)
- First, define a Person class that implements the JsonSerializable interface.
- Second, return an array that consists of name and age properties from the jsonSerialize() method. The json_encode() function will use the return value of this method to create JSON data.
- Third, create a new Person object and serialize it to JSON data using the json_encode() function.
Summary
- JSON is a lightweight data-interchange format.
- Use the json_encode() function to convert PHP variables to JSON.
- Use the json_decode() function to convert JSON data to PHP variables.
- Implement the JsonSerializable interface to specify the JSON representation of an object.