例-1:フォーマットせずにJSONを印刷する
json_encode() PHPの関数は、JSONデータを解析するために使用されます。名前の付いたファイルを作成します exp1.php 次のコードを使用して、単純なJSONデータを読み取り、出力を出力します。ここでは、JSONデータを生成するために連想配列が宣言されています。コード内のJSONデータにはフォーマットは適用されません。そのため、JSONデータはJSON形式で1行に出力されます。
exp1.php
<?php
//配列を宣言します
$ courses=配列((「モジュール1」=>>「HTML」、「モジュール2」=>>「JavaScript」、「モジュール3」=>>「CSS3」、
「モジュール4」=>>「PHP」)。;
//配列を印刷しますの単純なJSON形式
捨てたjson_encode(($ courses)。;
?>>
出力:
ブラウザからファイルを実行すると、次の出力が表示されます。
http://localhost/json/exp1.php
例-2:JSON_PRETTY_PRINTオプションとheader()関数を使用してJSONを印刷する
PHPにはという名前のオプションがあります ‘JSON_PRETTY_PRINT’ で使用されます json_encode() 適切な配置と特定の形式でJSONデータを印刷する関数。名前の付いたファイルを作成します exp2.php 次のコードで。コードでは、前の例と同じ配列を使用して使用法を確認しています JSON_PRETTY_PRINT オプション。 ヘッダ() 関数は、ファイルの内容についてブラウザに通知するためにここで使用されます。この機能がないとフォーマットは適用されません。
exp2.php
<?php//配列を宣言します
$ courses=配列((「モジュール1」=>>「HTML」、「モジュール2」=>>「JavaScript」、「モジュール3」=>>「CSS3」、
「モジュール4」=>>「PHP」)。;
//についてブラウザに通知しますタイプのファイルヘッダーを使用する関数
ヘッダ(('コンテンツタイプ:text / javascript')。;
//配列を印刷しますの単純なJSON形式
捨てたjson_encode(($ courses、JSON_PRETTY_PRINT)。;
?>>
出力:
ブラウザからファイルを実行すると、次の出力が表示されます。特定のフォントと配置が適用されます。
http://localhost/json/exp2.php
例-3: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を印刷する;
}
?>>
出力:
ブラウザからファイルを実行すると、次の出力が表示されます。ここでは、JSONデータの各質問と回答が次のように出力されます。 青 色と 大胆な フォーマットと、別の部分が印刷されます ネット 色。
http://localhost/json/exp4.php
結論
この記事では、さまざまなPHPオプションを使用してフォーマットされたJSONデータを印刷する方法を紹介します。上記の例を適切に実践した後、読者がPHPを適用してJSONデータをフォーマットし、きれいなJSON出力を生成できるようになることを願っています。