Пример-1: печать JSON без форматирования
json_encode () Функция PHP используется для анализа любых данных JSON. Создайте файл с именем exp1.php с помощью следующего кода, чтобы прочитать простые данные JSON и распечатать результат. Здесь объявлен ассоциативный массив для генерации данных JSON. Для данных JSON в коде форматирование не применяется. Итак, данные JSON будут напечатаны одной строкой в формате JSON.
exp1.php
<? php
//Объявить массив
$ курсы= массив('Модуль-1'знак равно>HTML,'Модуль-2'знак равно>'JavaScript','Модуль-3'знак равно>'CSS3',
'Модуль-4'знак равно>'PHP');
//Распечатать массиввпростой формат JSON
выбросилjson_encode($ курсы);
?>
Выход:
Следующий вывод появится после выполнения файла из браузера.
http: //localhost/json/exp1.php
Пример-2: печать JSON с использованием параметра JSON_PRETTY_PRINT и функции header ()
В PHP есть опция с именем «JSON_PRETTY_PRINT» который используется с json_encode () функция для печати данных JSON с правильным выравниванием и определенным форматом. Создайте файл с именем exp2.php со следующим кодом. В коде используется тот же массив из предыдущего примера, чтобы увидеть использование JSON_PRETTY_PRINT вариант. заголовок () Здесь функция используется для информирования браузера о содержимом файла. Без этой функции форматирование не применяется.
exp2.php
<? php//Объявить массив
$ курсы= массив('Модуль-1'знак равно>HTML,'Модуль-2'знак равно>'JavaScript','Модуль-3'знак равно>'CSS3',
'Модуль-4'знак равно>'PHP');
//Уведомить браузер отиппринадлежащийфайлиспользуя заголовокфункция
заголовок('Content-type: text / javascript');
//Распечатать массиввпростой формат JSON
выбросилjson_encode($ курсы, JSON_PRETTY_PRINT);
?>
Выход:
Следующий вывод появится после выполнения файла из браузера. Будет применен определенный шрифт и выравнивание.
http: //localhost/json/exp2.php
Пример-3: Печать JSON с использованием параметра JSON_PRETTY_PRINT и tag
The formatting that is applied in the previous example can be done by using ‘ pre ’ tag in place of header() function. Create a file named exp3.php with the following code. In this example, starting the ‘pre’ tag is used before generating JSON data. The output will be similar to the previous example.
exp3.php
<?php$data_arr = array('Robin Nixon' => 'Learning PHP, MySQL and JavaScript ',
'Jon Duckett' => 'HTML & CSS: Design and Build Web Sites', 'Rob Foster' =>
'CodeIgniter 2 Cookbook');
?>
<pre>
<?php
echo json_encode($data_arr, JSON_PRETTY_PRINT);
?>
pre>
Output:
The following output will appear after executing the file from the browser.
http://localhost/json/exp3.php
Example-4: Colorful JSON printing using the custom function
Formatted JSON data are printed by using JSON_PRETTY_PRINT option of PHP in the previous examples. But if you want to print JSON data with the custom format then it is better to use the user-defined function of PHP. How you can apply CSS in JSON data using PHP is mainly shown in this example. Create a PHP file named exp4.php with the following code. A large JSON data is used in this example that is stored in the variable, $data . A user-defined function, pretty_print() is used in the code to format the JSON data. This function has an argument that used to pass the JSON data. A for loop is used in the function to parse the JSON data and apply differently typed of formatting before printing the data.
exp4.php
<?php//Define a large json data
$data = '{'quiz bank':{ 'Computer': {'q1': { 'question': 'who is the inventor of
computer?','options': ['Thomas Alva Edison','Charles Babbage','Blaise Pascal',
'Philo Farnsworth'],'answer': 'Charles Babbage'},{'q2': { 'question':
'which of the following is a input device?', 'options': ['Printer','Scanner',
'Monitor', 'Keyboard'],'answer': 'Keyboard'}},'PHP': { 'q1': { 'question':
'What type of language is PHP?','options': ['High Level Language','Low level
Language','Scripting Language','Assembly Language'],'answer': 'Scripting Language' },
'q2': {'question': 'What is the full form of PHP?','options': ['Hypertext Preprocessor',
'Personal Home Package','Hypertext Processor','Perdonal HTML Page' ],'answer':
'Hypertext Preprocessor'} } } }';
//call custom function for formatting json data
echo pretty_print($data);
//Declare the custom function for formatting
function pretty_print($json_data)
{
//Initialize variable for adding space
$space = 0;
$flag = false;
//Using <pre> tag to format alignment and font
echo '
';
//loop for iterating the full json data
for($counter=0; $counter<strlen($json_data); $counter++)
{
//Checking ending second and third brackets
if ( $json_data[$counter] == '}' || $json_data[$counter] == ']' )
{
$space--;
echo ' ';
echo str_repeat(' ', ($space*2));
}
//Checking for double quote() and comma (,)
if ( $json_data[$counter] == ''' && ($json_data[$counter-1] == ',' ||
$json_data[$counter-2] == ',') )
{
echo ' ';
echo str_repeat(' ', ($space*2));
}
if ( $json_data[$counter] == ''' && !$flag )
$json_data[$counter-2] == ':' )
//Add formatting for question and answer
echo '';
else
//Add formatting for answer options
echo '';
echo $json_data[$counter];
//Checking conditions for adding closing span tag
if ( $json_data[$counter] == ''' && $flag )
echo '';
if ( $json_data[$counter] == ''' )
$flag = !$flag;
//Checking starting second and third brackets
if ( $json_data[$counter] == '{' || $json_data[$counter] == '[' )
{
$space++;
echo ' ';
echo str_repeat(' ', ($space*2));
}
}
echo ' ';
}
?>
Выход:
Следующий вывод появится после выполнения файла из браузера. Здесь каждый вопрос и ответ данных JSON будут напечатаны с синий цвет и жирный формат и другая часть будет напечатана с сеть цвет.
http: //localhost/json/exp4.php
Заключение
В этой статье мы попытаемся показать, как вы можете распечатать форматированные данные JSON с помощью различных параметров PHP. Надеюсь, читатель сможет применить PHP для форматирования данных JSON и сгенерировать красивый вывод JSON после того, как правильно попрактикуется в приведенных выше примерах.