Cómo leer e imprimir JSON bonito con PHP

How Read Print Pretty Json With Php



JSON es un formato de almacenamiento de datos popular para intercambiar datos entre el servidor y el navegador. Se deriva de JavaScript y es compatible con muchos lenguajes de programación estándar. Es un formato de archivo legible por humanos que cualquiera puede entender fácilmente si se imprime con el formato adecuado. Los datos JSON se imprimen en una sola línea cuando no se aplica ningún formato. Pero este tipo de resultado no es tan fácil de entender. Por lo tanto, los datos JSON formateados son muy importantes para comprender la estructura de los datos para el lector. Pretty Print se utiliza para formatear los datos JSON. Los datos JSON se pueden representar en una forma más legible para los humanos mediante el uso de una impresión bonita. Hay muchas formas de aplicar una impresión bonita en datos JSON. En este tutorial se muestra cómo puede aplicar la impresión bonita JSON usando PHP utilizando varios ejemplos.

Ejemplo 1: imprimir JSON sin formatear

json_encode () La función de PHP se utiliza para analizar cualquier dato JSON. Crea un archivo llamado exp1.php con el siguiente código para leer datos JSON simples e imprimir la salida. Aquí, se declara una matriz asociativa para generar datos JSON. No se aplica formato a los datos JSON en el código. Entonces, los datos JSON se imprimirán en una sola línea en formato JSON.







exp1.php



<? php

//Declarar la matriz
$ cursos= matriz('Módulo 1'=>'HTML','Módulo-2'=>'JavaScript','Módulo-3'=>'CSS3',
'Módulo-4'=>'PHP');

//Imprime la matrizenun formato JSON simple
echojson_encode($ cursos);
?>

Producción:



La siguiente salida aparecerá después de ejecutar el archivo desde el navegador.





http: //localhost/json/exp1.php



Ejemplo-2: Imprimir JSON usando la opción JSON_PRETTY_PRINT y la función header ()

PHP tiene una opción llamada 'JSON_PRETTY_PRINT' que se usa con json_encode () función para imprimir datos JSON con la alineación adecuada y un formato particular. Crea un archivo llamado exp2.php con el siguiente código. En el código, se usa la misma matriz del ejemplo anterior para ver el uso JSON_PRETTY_PRINT opción. encabezamiento() La función se utiliza aquí para informar al navegador sobre el contenido del archivo. No se aplicará ningún formato sin esta función.

exp2.php

<? php
//Declarar la matriz
$ cursos= matriz('Módulo 1'=>'HTML','Módulo-2'=>'JavaScript','Módulo-3'=>'CSS3',
'Módulo-4'=>'PHP');

//Notifique al navegador sobre elescribede Elexpedienteusando el encabezadofunción
encabezamiento('Tipo de contenido: texto / javascript');

//Imprime la matrizenun formato JSON simple
echojson_encode($ cursos, JSON_PRETTY_PRINT);
?>

Producción:

La siguiente salida aparecerá después de ejecutar el archivo desde el navegador. Se aplicará una fuente y una alineación específicas.

http: //localhost/json/exp2.php

Ejemplo-3: Imprima JSON usando la opción JSON_PRETTY_PRINT y
 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 '
'
;
}
?>

Producción:

La siguiente salida aparecerá después de ejecutar el archivo desde el navegador. Aquí, cada pregunta y respuesta de los datos JSON se imprimirá con azul color y negrita formato y, otra parte se imprimirá con red color.

http: //localhost/json/exp4.php

Conclusión

En este artículo se intenta mostrar cómo puede imprimir datos JSON formateados utilizando varias opciones de PHP. Espero que el lector pueda aplicar PHP para formatear datos JSON y generar una salida JSON bonita después de practicar correctamente los ejemplos anteriores.