在PHP中,我们可以通过以下方式设置Content-Type:
header('Content-Type: text/plain');
Run Code Online (Sandbox Code Playgroud)
但是,如果我处理需要显示错误消息的PHP类,根据内容类型显示错误消息的格式,例如,如果页面是text/html,则显示HTML格式的错误消息; 否则,显示纯文本错误消息.
是否有任何功能/片段可用于检测页面内容类型?
注意:假定PHP类文件被"附加"到页面上 require_once()
更新:从@Tamil的回答中,我进行了一个简短的测试:
<?php
header('Content-Type: text/plain');
$finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
echo finfo_file($finfo, __FILE__) . "\n";
finfo_close($finfo);
?>
Run Code Online (Sandbox Code Playgroud)
它只返回text/x-php.但我希望结果会回归text/plain.
尝试headers_list()功能:
<?php
header('Content-Type: text/plain');
$headers = headers_list();
var_dump($headers);
?>
Run Code Online (Sandbox Code Playgroud)
显示(在我的情况下):
array(2) {
[0]=>
string(23) "X-Powered-By: PHP/5.4.5"
[1]=>
string(24) "Content-Type: text/plain"
}
Run Code Online (Sandbox Code Playgroud)
要规范化结果数组,您可以使用:
<?php
header('Content-Type: text/plain');
$headers = headers_list();
foreach($headers as $index => $value) {
list($key, $value) = explode(': ', $value);
unset($headers[$index]);
$headers[$key] = $value;
}
var_dump($headers);
?>
Run Code Online (Sandbox Code Playgroud)
显示:
array(2) {
["X-Powered-By"]=>
string(9) "PHP/5.4.5"
["Content-Type"]=>
string(10) "text/plain"
}
Run Code Online (Sandbox Code Playgroud)
因此,Content-Type带有规范化数组的标头可能会像这样获得:
echo $headers['Content-Type'];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1169 次 |
| 最近记录: |