How to select content type from HTTP Accept header in PHP

后端 未结 7 1029
[愿得一人]
[愿得一人] 2020-12-16 13:10

I\'m trying to build a standard compliant website framework which serves XHTML 1.1 as application/xhtml+xml or HTML 4.01 as text/html depending on the browser support. Curre

7条回答
  •  失恋的感觉
    2020-12-16 13:31

    Little snippet from my library:

    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;
    }
    

    example usage:

    $mime = getBestSupportedMimeType(Array ('application/xhtml+xml', 'text/html'));
    

提交回复
热议问题