Ví dụ-1: In JSON mà không cần định dạng
json_encode () hàm của PHP được sử dụng để phân tích cú pháp bất kỳ dữ liệu JSON nào. Tạo một tệp có tên exp1.php với đoạn mã sau để đọc dữ liệu JSON đơn giản và in đầu ra. Ở đây, một mảng kết hợp được khai báo để tạo dữ liệu JSON. Không có định dạng nào được áp dụng cho dữ liệu JSON trong mã. Vì vậy, dữ liệu JSON sẽ được in trên một dòng duy nhất ở định dạng JSON.
exp1.php
<? php
//Khai báo mảng
khóa học $= mảng('Mô-đun 1'=>'HTML','Mô-đun-2'=>'JavaScript','Mô-đun-3'=>'CSS3',
'Mô-đun-4'=>'PHP');
//In mảngtrongmột định dạng JSON đơn giản
quăng đijson_encode(khóa học $);
?>
Đầu ra:
Kết quả sau sẽ xuất hiện sau khi thực thi tệp từ trình duyệt.
http: //localhost/json/exp1.php
Ví dụ-2: In JSON bằng cách sử dụng tùy chọn JSON_PRETTY_PRINT và hàm header ()
PHP có một tùy chọn có tên ‘JSON_PRETTY_PRINT’ được sử dụng với json_encode () chức năng in dữ liệu JSON với căn chỉnh thích hợp và định dạng cụ thể. Tạo một tệp có tên exp2.php với đoạn mã sau. Trong mã, cùng một mảng của ví dụ trước đó được sử dụng để xem việc sử dụng JSON_PRETTY_PRINT Lựa chọn. tiêu đề () chức năng được sử dụng ở đây để thông báo cho trình duyệt về nội dung tệp. Không có định dạng nào sẽ được áp dụng nếu không có chức năng này.
exp2.php
<? php//Khai báo mảng
khóa học $= mảng('Mô-đun 1'=>'HTML','Mô-đun-2'=>'JavaScript','Mô-đun-3'=>'CSS3',
'Mô-đun-4'=>'PHP');
//Thông báo cho trình duyệt vềkiểusau đótập tinsử dụng tiêu đềhàm số
tiêu đề('Content-type: text / javascript');
//In mảngtrongmột định dạng JSON đơn giản
quăng đijson_encode(khóa học $, JSON_PRETTY_PRINT);
?>
Đầu ra:
Kết quả sau sẽ xuất hiện sau khi thực thi tệp từ trình duyệt. Một phông chữ cụ thể và căn chỉnh sẽ được áp dụng.
http: //localhost/json/exp2.php
Ví dụ-3: In JSON bằng cách sử dụng tùy chọn JSON_PRETTY_PRINT và 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 ' ';
}
?>
Đầu ra:
Kết quả sau sẽ xuất hiện sau khi thực thi tệp từ trình duyệt. Tại đây, mỗi câu hỏi và câu trả lời của dữ liệu JSON sẽ được in bằng màu xanh dương màu sắc và in đậm định dạng và một phần khác sẽ được in với mạng lưới màu sắc.
http: //localhost/json/exp4.php
Phần kết luận
Cách bạn có thể in dữ liệu JSON được định dạng bằng cách sử dụng các tùy chọn PHP khác nhau sẽ được trình bày trong bài viết này. Hy vọng, người đọc sẽ có thể áp dụng PHP để định dạng dữ liệu JSON và tạo ra đầu ra JSON khá tốt sau khi thực hành đúng các ví dụ trên.