2011-11-30 79 views
4

我使用PHP,並且想知道如何通過Internationalization擴展(ICAP庫的Wrapper)獲取區域設置的默認貨幣?如何從PHP Intl(ICU庫)獲取默認貨幣

下面是解釋,什麼和爲什麼的腳本。 我需要一些東西來替換getCurrCode()函數。

$accepted_currencies = array('USD','EUR'); 
$locale = Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']); 
if(! empty($locale)){ 
    Locale::setDefault($locale); 
    $currency = getCurrCode(); 
    if(! in_array($currency, $accepted_currencies)){ 
     $currency = 'USD'; 
    } 
}else{ 
    Locale::setDefault('en_US'); 
} 

$fmt = new NumberFormatter($locale, NumberFormatter::CURRENCY); 
$price = $fmt->formatCurrency(1234567.891234567890000, $currency); 

我知道,我可以使用setlocale(LC_MONETARY, $locale);但是這意味着我必須安裝所有的語言環境到Linux和處理的Linux發行版的變化。那麼在第一個地方使用Intl會有什麼意義呢?

回答

10

一旦您設置的Locale到的NumberFormatter,你可以用

$formatter = new NumberFormatter('de_DE', NumberFormatter::CURRENCY); 
echo $formatter->getTextAttribute(NumberFormatter::CURRENCY_CODE); 

$formatter = new NumberFormatter('en_US', NumberFormatter::CURRENCY); 
echo $formatter->getTextAttribute(NumberFormatter::CURRENCY_CODE); 

$formatter = new NumberFormatter('ja_JP', NumberFormatter::CURRENCY); 
echo $formatter->getTextAttribute(NumberFormatter::CURRENCY_CODE); 

上面獲取貨幣代碼會給歐元,美元和日元。

+0

謝謝,它的工作原理。 – RoboTamer

+0

真棒,救了我很多工作...謝謝 –

+0

在不丹,有2種貨幣(BTN和INR),但你的示例代碼只返回一個(BTN):( –