header() 函数向客户端发送原始的 HTTP 报头,作用是把括号里面的信息发到http标头
认识到一点很重要,即必须在任何实际的输出被发送之前调用 header() 函数(在 PHP 4 以及更高的版本中,您可以使用输出缓存来解决此问题):
注意:在调用header函数之前不能有任何输出
void header ( string$string [, bool$replace = true [, int$http_response_code ]] )
参数描述
string 必需。规定要发送的报头字符串。
replace 可选。指示该报头是否替换之前的报头,或添加第二个报头。默认是 true(替换)。false(允许相同类型的多个报头)。
http_response_code 可选。把 HTTP 响应代码强制为指定的值。(PHP 4 以及更高版本可用)
举例:
header("Status: 404 Not Found");
header('Location: http://www.example.com/');
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Cache-Control: no-cache");
header("Pragma: no-cache");
header("Content-type:application/pdf");
header("Content-type: text/html; charset=utf-8");
同样可以设置字符集但是header设置的要比meta设置的优先级高,因为header发送的内容先到达浏览器
输出XML
header("Content-type: text/xml");
输出json
第一种 header('Content-type: application/json'); 另一种 header('Content-type: text/json');