PHP 怎么PHP 响应发送

wen PHP项目 1

本文目录导读:

PHP 怎么PHP 响应发送

  1. 基础文本/HTML 响应
  2. 设置响应头
  3. 返回 JSON 响应(API 开发常用)
  4. 重定向响应
  5. 文件下载响应
  6. 流式响应(分块发送大文件)
  7. 完整的响应封装类
  8. 重要注意事项

在 PHP 中响应发送(即向客户端返回数据)有多种方式,具体取决于你要发送的内容类型(HTML、JSON、文件下载等),以下是几种常见场景的完整实现:


基础文本/HTML 响应

<?php
// 直接输出字符串
echo "Hello, World!";
// 输出 HTML
echo "<h1>欢迎</h1><p>这是PHP响应</p>";
// 使用 print 函数
print "这是另一行输出\n";
?>

设置响应头

<?php
// 必须在任何输出之前调用 header()
header('Content-Type: text/html; charset=utf-8');
header('X-Custom-Header: MyValue');
// 设置状态码
http_response_code(200); // 成功
// http_response_code(404); // 未找到
// http_response_code(500); // 服务器错误
echo "响应带自定义头部";
?>

返回 JSON 响应(API 开发常用)

<?php
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *'); // CORS 跨域
$data = [
    'status' => 'success',
    'code' => 200,
    'message' => '数据获取成功',
    'data' => [
        'id' => 1,
        'name' => '张三',
        'email' => 'zhangsan@example.com'
    ]
];
echo json_encode($data, JSON_UNESCAPED_UNICODE);
?>

更好的封装方式:

<?php
function jsonResponse($data, $statusCode = 200) {
    http_response_code($statusCode);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($data, JSON_UNESCAPED_UNICODE);
    exit;
}
// 使用
jsonResponse(['message' => '操作成功', 'id' => 123]);
?>

重定向响应

<?php
// 方式一:直接重定向
header('Location: https://example.com/new-page.php');
exit; // 必须加 exit 停止后续执行
// 方式二:延迟重定向
header('Refresh: 3; url=https://example.com');
echo "3秒后跳转...";
// 方式三:带状态码的重定向(301永久/302临时)
header('Location: /new-url.php', true, 301);
exit;
?>

文件下载响应

<?php
$file = 'document.pdf';
if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment; filename="'.basename($file).'"');
    header('Content-Length: ' . filesize($file));
    header('Cache-Control: no-cache');
    readfile($file);
    exit;
} else {
    http_response_code(404);
    echo "文件不存在";
}
?>

流式响应(分块发送大文件)

<?php
header('Content-Type: text/plain; charset=utf-8');
// 设置缓冲区大小
ob_implicit_flush(true);
ob_start('', 4096);
for ($i = 1; $i <= 10; $i++) {
    echo "数据块 $i\n";
    ob_flush();  // 立即发送到客户端
    flush();     // 刷新输出缓冲区
    sleep(1);    // 模拟延迟
}
?>

完整的响应封装类

<?php
class Response {
    public static function send($content, $statusCode = 200, $contentType = 'text/html') {
        http_response_code($statusCode);
        header('Content-Type: ' . $contentType);
        if (is_array($content) || is_object($content)) {
            echo json_encode($content, JSON_UNESCAPED_UNICODE);
        } else {
            echo $content;
        }
        exit;
    }
    public static function json($data, $statusCode = 200) {
        self::send($data, $statusCode, 'application/json');
    }
    public static function redirect($url, $statusCode = 302) {
        header('Location: ' . $url, true, $statusCode);
        exit;
    }
    public static function download($filePath, $filename = null) {
        if (!file_exists($filePath)) {
            self::send('文件不存在', 404);
        }
        $filename = $filename ?? basename($filePath);
        $mimeType = mime_content_type($filePath);
        header('Content-Type: ' . $mimeType);
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Content-Length: ' . filesize($filePath));
        readfile($filePath);
        exit;
    }
}
// 使用示例
// Response::json(['msg' => '成功']);
// Response::redirect('/login');
// Response::download('report.pdf');
?>

重要注意事项

  1. 输出前不能有空格/HTML
    header() 函数必须在任何实际输出之前调用,包括空格、HTML 标签或 echo 的输出。

  2. 使用 exit 终止
    发送完响应后建议调用 exit,防止后续代码意外输出。

  3. 缓冲区处理
    如果遇到 Cannot modify header information 错误,可用 ob_start() 开启输出缓冲。

  4. 状态码选择

    • 200:成功
    • 301:永久重定向
    • 302:临时重定向
    • 404:未找到
    • 500:服务器错误

根据你的实际需求选择最合适的响应方式,如果是开发 API,推荐使用 JSON 响应;如果是传统网站,直接输出 HTML 即可。

上一篇PHP 怎么PHP 响应压缩

下一篇当前分类已是最新一篇

抱歉,评论功能暂时关闭!