我正在尝试构建一个标准的兼容网站框架,它根据浏览器支持将 XHTML 1.1 作为 application/xhtml+xml 或将 HTML 4.01 作为 text/html 提供服务。目前它只是在 accept header 中的任何位置查找“application/xhtml+xml”,如果它存在就使用它,但这不灵活——text/html 可能有更高的分数。此外,当添加其他格式(WAP、SVG、XForms 等)时,它会变得更加复杂。那么,有没有人知道一段久经考验的 PHP 代码,可以从服务器提供的字符串数组中选择最受客户端支持的代码或基于客户端评分的有序列表?
最佳答案
我的图书馆的小片段:
function getBestSupportedMimeType($mimeTypes = null) {
// Values will be stored in this array
$AcceptTypes = Array ();
// Accept header is case insensitive, and whitespace isn’t important
$accept = strtolower(str_replace(' ', '', $_SERVER['HTTP_ACCEPT']));
// divide it into parts in the place of a ","
$accept = explode(',', $accept);
foreach ($accept as $a) {
// the default quality is 1.
$q = 1;
// check if there is a different quality
if (strpos($a, ';q=')) {
// divide "mime/type;q=X" into two parts: "mime/type" i "X"
list($a, $q) = explode(';q=', $a);
}
// mime-type $a is accepted with the quality $q
// WARNING: $q == 0 means, that mime-type isn’t supported!
$AcceptTypes[$a] = $q;
}
arsort($AcceptTypes);
// if no parameter was passed, just return parsed data
if (!$mimeTypes) return $AcceptTypes;
$mimeTypes = array_map('strtolower', (array)$mimeTypes);
// let’s check our supported types:
foreach ($AcceptTypes as $mime => $q) {
if ($q && in_array($mime, $mimeTypes)) return $mime;
}
// no mime-type found
return null;
}
示例用法:
$mime = getBestSupportedMimeType(Array ('application/xhtml+xml', 'text/html'));
关于php - 如何从 PHP 中的 HTTP Accept header 中选择内容类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1049401/