Created
October 22, 2011 23:03
-
-
Save dantman/1306599 to your computer and use it in GitHub Desktop.
lang.php to parse accept-lang and return it as json for js to fetch and handle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
define('MEDIAWIKI', 1); | |
require_once dirname( __FILE__ ) . '/languages/Names.php'; | |
require_once dirname( __FILE__ ) . '/includes/json/FormatJson.php'; | |
// Based on http://www.thefutureoftheweb.com/blog/use-accept-language-header | |
$langs = array(); | |
if ( isset( $_SERVER['HTTP_ACCEPT_LANGUAGE'] ) ) { | |
// break up string into pieces (languages and q factors) | |
preg_match_all('/([a-z]+(?:-[a-z]+)?)\s*(?:;\s*q\s*=\s*(1|0?\.[0-9]+))?/i', $_SERVER['HTTP_ACCEPT_LANGUAGE'], $lang_parse); | |
if ( count( $lang_parse[1] ) > 0 ) { | |
// create a list like "en" => 0.8 | |
foreach ( $lang_parse[1] as $i => $code ) { | |
if ( isset( $lang_parse[2][$i] ) && $lang_parse[2][$i] != '' ) { | |
$langs[strtolower($code)] = (float) $lang_parse[2][$i]; | |
} else { | |
$langs[strtolower($code)] = 1; | |
} | |
} | |
// sort list based on value | |
arsort($langs, SORT_NUMERIC); | |
} | |
} | |
foreach ( $langs as $code => $q ) { | |
if ( !isset( $coreLanguageNames[$code] ) ) { | |
unset( $langs[$code] ); | |
} | |
} | |
$out = array(); | |
foreach ( $langs as $code => $q ) { | |
$out[] = (object) array( | |
'code' => $code, | |
'name' => $coreLanguageNames[$code], | |
); | |
} | |
//header( 'Content-type: application/json; charset=UTF-8' ); // @real | |
header( 'Content-type: text/plain; charset=UTF-8' ); // @debug | |
header( 'Cache-Control: private, s-maxage=0, max-age=' . (60*60*24) ); | |
header( 'Vary: Accept-Language' ); | |
echo FormatJson::encode( $out ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment