本文目录导读:

我来详细说明PHP如何生成响应:
基础响应输出
直接输出
<?php
// 直接输出文本
echo "Hello World";
// 输出变量
$name = "PHP";
echo "Hello, " . $name;
// print 函数
print "Hello World\n";
// 输出格式化字符串
printf("数字:%d,字符串:%s", 42, "test");
?>
设置HTTP响应头
<?php类型
header('Content-Type: text/html; charset=utf-8');
// 设置JSON响应
header('Content-Type: application/json');
// 设置下载文件
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="file.txt"');
// 设置缓存控制
header('Cache-Control: no-cache, must-revalidate');
// 设置状态码
http_response_code(200); // 成功
http_response_code(404); // 未找到
http_response_code(500); // 服务器错误
?>
不同类型的响应
HTML响应
<?php
header('Content-Type: text/html; charset=utf-8');
?>
<!DOCTYPE html>
<html>
<head>PHP响应</title>
</head>
<body>
<h1><?php echo "动态内容"; ?></h1>
<p>当前时间:<?php echo date('Y-m-d H:i:s'); ?></p>
</body>
</html>
JSON响应
<?php
header('Content-Type: application/json');
$data = [
'status' => 'success',
'message' => '操作成功',
'data' => [
'id' => 1,
'name' => '张三'
]
];
echo json_encode($data, JSON_UNESCAPED_UNICODE);
?>
XML响应
<?php
header('Content-Type: text/xml; charset=utf-8');
$xml = new SimpleXMLElement('<root/>');
$xml->addChild('status', 'success');
$xml->addChild('message', '操作成功');
echo $xml->asXML();
?>
文件下载响应
<?php
$file = 'path/to/file.pdf';
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
}
?>
重定向响应
<?php
// 简单重定向
header('Location: /new-page.php');
exit;
// 带有状态码的重定向
header('Location: /new-page.php', true, 301); // 永久重定向
header('Location: /new-page.php', true, 302); // 临时重定向
exit;
?>
流式响应(大文件传输)
<?php
header('Content-Type: text/plain');
header('Content-Disposition: attachment; filename="large.txt"');
// 生成大量数据
for ($i = 0; $i < 1000000; $i++) {
echo "Line $i: " . str_repeat("data", 100) . "\n";
// 刷新输出缓冲区
if ($i % 1000 == 0) {
ob_flush();
flush();
}
}
?>
完整示例:API响应类
<?php
class Response {
public static function json($data, $statusCode = 200) {
http_response_code($statusCode);
header('Content-Type: application/json; charset=utf-8');
echo json_encode($data, JSON_UNESCAPED_UNICODE);
exit;
}
public static function success($data = null, $message = '成功') {
return self::json([
'code' => 200,
'message' => $message,
'data' => $data
]);
}
public static function error($message = '失败', $code = 400) {
return self::json([
'code' => $code,
'message' => $message
], $code);
}
public static function redirect($url) {
header('Location: ' . $url);
exit;
}
public static function download($filepath, $filename = null) {
if (!file_exists($filepath)) {
self::error('文件不存在', 404);
}
$filename = $filename ?? basename($filepath);
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Content-Length: ' . filesize($filepath));
readfile($filepath);
exit;
}
}
// 使用示例
// Response::success(['user' => ['name' => '张三']]);
// Response::error('未授权访问', 401);
// Response::redirect('/login');
// Response::download('/path/to/file.pdf', 'document.pdf');
?>
注意事项
-
输出前不能有输出:在
header()函数之前不能有任何输出(包括HTML空格) -
使用输出缓冲:
<?php ob_start(); // 开启输出缓冲 // ... 代码 ob_end_flush(); // 输出并关闭缓冲 ?>
-
清除输出:
<?php ob_clean(); // 清除缓冲区内容 // 或 ob_end_clean(); // 清除并关闭缓冲 ?>
这些是PHP生成响应的主要方式,根据具体需求选择合适的方法。