Exemple-1: imprimiu JSON sense formatar
json_encode () La funció de PHP s'utilitza per analitzar qualsevol dada JSON. Creeu un fitxer anomenat exp1.php amb el codi següent per llegir dades senzilles JSON i imprimir la sortida. Aquí es declara una matriu associativa per generar dades JSON. No s’aplica cap format per a les dades JSON del codi. Per tant, les dades JSON s’imprimiran en una sola línia en format JSON.
exp1.php
<? php
//Declareu la matriu
$ cursos= matriu('Mòdul-1'=>'HTML','Mòdul-2'=>'JavaScript','Mòdul-3'=>'CSS3',
'Mòdul-4'=>'PHP');
//Imprimiu la matriudinsun format JSON senzill
trobojson_encode($ cursos);
?>
Sortida:
La següent sortida apareixerà després d'executar el fitxer des del navegador.
http: //localhost/json/exp1.php
Exemple-2: imprimiu JSON mitjançant l'opció JSON_PRETTY_PRINT i la funció header ()
PHP té una opció anomenada 'JSON_PRETTY_PRINT' que s’utilitza amb json_encode () funció per imprimir dades JSON amb l'alineació adequada i un format particular. Creeu un fitxer anomenat exp2.php amb el següent codi. Al codi, s'utilitza la mateixa matriu de l'exemple anterior per veure'n l'ús JSON_PRETTY_PRINT opció. capçalera () aquí s’utilitza la funció per informar el navegador sobre el contingut del fitxer. No s’aplicarà cap format sense aquesta funció.
exp2.php
<? php//Declareu la matriu
$ cursos= matriu('Mòdul-1'=>'HTML','Mòdul-2'=>'JavaScript','Mòdul-3'=>'CSS3',
'Mòdul-4'=>'PHP');
//Notifiqueu al navegador el fitxertipusdeldossierutilitzant la capçalerafunció
capçalera('Tipus de contingut: text / javascript');
//Imprimiu la matriudinsun format JSON senzill
trobojson_encode($ cursos, JSON_PRETTY_PRINT);
?>
Sortida:
La següent sortida apareixerà després d'executar el fitxer des del navegador. S’aplicarà un tipus de lletra i un alineament específics.
http: //localhost/json/exp2.php
Exemple-3: imprimiu JSON mitjançant l'opció JSON_PRETTY_PRINT i 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 ' ';
}
?>
Sortida:
La següent sortida apareixerà després d'executar el fitxer des del navegador. Aquí s’imprimirà amb cada pregunta i resposta de les dades JSON blau color i atrevit i s'imprimirà una altra part amb xarxa color.
http: //localhost/json/exp4.php
Conclusió
En aquest article es mostra com es poden imprimir dades JSON amb format mitjançant diverses opcions de PHP. Esperem que el lector pugui aplicar el PHP per formatar dades JSON i generar una sortida JSON bonica després de practicar correctament els exemples anteriors.