使用PHP的json_encode()函數來將數據轉換為JSON格式并輸出。示例代碼如下:
$data = array("name" => "John", "age" => 30, "city" => "New York");
$json = json_encode($data);
echo $json;
上面的代碼將數組$data轉換為JSON格式并輸出。如果需要將JSON數據返回給前端頁面,可以使用header()函數設置Content-Type為application/json,然后直接輸出JSON數據。示例代碼如下:
$data = array("name" => "John", "age" => 30, "city" => "New York");
$json = json_encode($data);
header('Content-Type: application/json');
echo $json;