Exemplo-1: Imprimir JSON sem formatação
json_encode () A função do PHP é usada para analisar quaisquer dados JSON. Crie um arquivo chamado exp1.php com o código a seguir para ler dados JSON simples e imprimir a saída. Aqui, uma matriz associativa é declarada para gerar dados JSON. Nenhuma formatação é aplicada para dados JSON no código. Portanto, os dados JSON serão impressos em uma única linha no formato JSON.
exp1.php
<? php
//Declare a matriz
$ cursos= array('Módulo 1'=>'HTML','Módulo-2'=>'JavaScript','Módulo-3'=>'CSS3',
'Módulo-4'=>'PHP');
//Imprima a matriznoum formato JSON simples
jogou forajson_encode($ cursos);
?>
Saída:
A seguinte saída aparecerá após a execução do arquivo no navegador.
http: //localhost/json/exp1.php
Exemplo-2: Imprimir JSON usando a opção JSON_PRETTY_PRINT e a função header ()
PHP tem uma opção chamada ‘JSON_PRETTY_PRINT’ que é usado com json_encode () função para imprimir dados JSON com alinhamento adequado e formato particular. Crie um arquivo chamado exp2.php com o seguinte código. No código, a mesma matriz do exemplo anterior é usada para ver o uso JSON_PRETTY_PRINT opção. cabeçalho() A função é usada aqui para informar o navegador sobre o conteúdo do arquivo. Nenhuma formatação será aplicada sem esta função.
exp2.php
<? php//Declare a matriz
$ cursos= array('Módulo 1'=>'HTML','Módulo-2'=>'JavaScript','Módulo-3'=>'CSS3',
'Módulo-4'=>'PHP');
//Notifique o navegador sobre omodelodoArquivousando cabeçalhofunção
cabeçalho('Content-type: text / javascript');
//Imprima a matriznoum formato JSON simples
jogou forajson_encode($ cursos, JSON_PRETTY_PRINT);
?>
Saída:
A seguinte saída aparecerá após a execução do arquivo no navegador. Uma fonte e um alinhamento específicos serão aplicados.
http: //localhost/json/exp2.php
Exemplo-3: Imprimir JSON usando a opção JSON_PRETTY_PRINT e 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 ' ';
}
?>
Saída:
A seguinte saída aparecerá após a execução do arquivo no navegador. Aqui, cada pergunta e resposta dos dados JSON será impressa com azul cor e negrito formato e, outra parte será impressa com internet cor.
http: //localhost/json/exp4.php
Conclusão
Como você pode imprimir dados JSON formatados usando várias opções de PHP são mostrados neste artigo. Espero que o leitor seja capaz de aplicar o PHP para formatar dados JSON e gerar uma saída JSON bonita depois de praticar os exemplos acima corretamente.