Json methods in php

PHP JSON and Callback functions

In this article, you will learn about JSON format and its available PHP functions. Also, we will look at the Callback functions in PHP. So, let’s start.

What is JSON?

JSON stands for Javascript Object Notation. It is a structure to represent the data in a more readable form. JSON is used all over the world by almost all languages, therefore it plays an important role in making cross-platform requests and getting responses.

Every language is capable of reading JSON so, most of the API calls are used JSON input data and response output. There are some built-in JSON functions in PHP.

json_encode is used to encode or convert a value into JSON formate. Look at the example below.

35, "Ben"=>37, "Joe"=>43); echo json_encode($age); ?>

json_decode is used to convert or decode back the JSON object into an associative array (key-value pairs) or a PHP value. Look at the following example.

'; var_dump(json_decode($jsonobj)); ?>

The second parameter of json_decode is a boolean. If it is set to false, it returns an object. If it is set to true, it returns an associative array. The following example makes use of the second parameter of json_decode.

'; var_dump(json_decode($jsonobj, true)); ?>

How to access the json_decode return values?

As we see above that json_decode returns an object by default and an associative array when the second parameter becomes true. We will show you examples to access values from each of these outputs.

Читайте также:  Java задать многомерный массив

Example 1 – json_decode returns object

'; $obj = json_decode($jsonobj); echo $obj->Peter; echo $obj->Ben; echo $obj->Joe; ?>

Example 2 – json_decode returns an associative array

'; $arr = json_decode($jsonobj, true); echo $arr["Peter"]; echo $arr["Ben"]; echo $arr["Joe"]; ?>

How to loop through the json_decode array?

As we know, json_decode returns an associative array. So, foreach loop can access both the keys and their values in json_decode. Look at the following example in which we iterate over the json_decode result.

'; $arr = json_decode($jsonobj, true); echo $arr["Peter"]; echo $arr["Ben"]; echo $arr["Joe"]; ?>

Callback functions in PHP

A function passed as an argument to another function is called a callback function. You can define your own callback function and pass it to another function. In this case, just pass the name of the function as a string. Look at the following example of a simple callback function in PHP.

 $strings = ["apple", "orange", "banana", "coconut"]; $lengths = array_map("my_callback", $strings); print_r($lengths); ?>

PHP 7 and 8 can now pass an anonymous function as a callback function. In the following example, you will learn how to pass an anonymous function as a callback function in PHP.

How to use user-defined function as callback function?

Just like a normal function, use argument variables in your function. Now, pass this function as a callback function.

 function ask($str) < return $str . "? "; >function printFormatted($str, $format) < // Calling the $format callback function echo $format($str); >// Pass "exclaim" and "ask" as callback functions to printFormatted() printFormatted("Hello world", "exclaim"); printFormatted("Hello world", "ask"); ?>

As you are now familiar with the JSON format, json_encode, json_decode, and callback functions in PHP. In the next section, we will learn about two simple, but very easy, and important concepts of PHP.

What is include keyword in PHP?

Include the keyword in PHP allows using an external file having PHP script, in the current file. It saves us from writing the code of the file again and again everywhere we want to use its code.

Without using the include keyword, the code can be messy or redundant. To solve the problem of redundancy, PHP provides two keywords, include and require. Logically, they do the same thing but are different from each other. Let’s go through them one by one!

What is the difference between include and require in PHP?

include require
Include keyword allows to use the piece of code in some external file, into your existing code. Just add the file at the top of the PHP script using the include keyword and you can access the code of that file in your current code. Here, the important thing is, if the file you specify in the include keyword does not exist or contains any error in it. It will produce E_WARNING but does not stop your script. On the other hand, require keyword is also used to add external code files into the current PHP script. But on any kind of failure in the file, or in the case of a missing file, require the function to produce E_COMPILE_ERROR and does not allow the script to execute. It will stop the process.

PHP Include vs Require

Which is better to use out of include or require?

The choice between include and require depends on the use case or scenario.

If you are working on a platform in which high security is the main concern. In this case, you must use the required keyword. As the required keyword does not allow the script to execute for any error in the attached file or in case of file not found.

If you want your script not to stop due to the included file, you can use the include function in this case. It will acknowledge you about the problem using the E_WARNING error.

Syntax of include and require

include 'filename'; or require 'filename';

Learn more about this topic in the official documentation about json_encode, json_decode, and PHP callback functions.

Источник

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

Источник

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