php:zf2多货币实现

时间:2015-10-27 16:10:02

标签: php zend-framework2

我是zf2的新手。在我目前的网站中,我需要实施多种货币选择。我所做的是在应用程序模块中创建一个.global文件,并添加了下面的列表

return array(
    'currency' =>array(
        'default_currency'=>'GBP',
        'currency_list'=> array(
            'GBP'=>'UK(£)',
            'USD'=>'USA($)',
            'EUR'=>'EU Euro(€)',
            'HKD'=>'HK Dollar(HKD)',
            'CHF'=>'Swiss Franc(CHF)',
            'JPY'=>'Japan Yen(¥)',
            'SGD'=>'Sing Dollar(SGD)'
        )
    )
);

以上列表将显示在我的菜单栏中。需要的是当用户选择货币时,网站必须将该货币设置为整个网站的默认货币。 我在Module.php的bootstrap函数中执行此操作,但它无法正常工作。

$eventManager->attach('route', function ($event) {
                $sm = $event->getApplication()->getServiceManager();
                $config = $event->getApplication()->getServiceManager()->get('Configuration');
                // locale language
                $localesConfig = $config['locales'];
                $locales = $localesConfig['lang_list'];
                $locale = $event->getRouteMatch()->getParam('locale');

                $localeCurrencyConfig = $config['currency'];
                $localesCurrency = $localeCurrencyConfig['currency_list'];
                $localeCurrency = $event->getRouteMatch()->getParam('curr');

                // unsupported lacale provided default to en 
                if (!in_array($locale, array_keys($locales)))
                    $locale = $localesConfig['default_lang'];
                // unsupported currency provided default to GBP
                if (!in_array($localeCurrency, array_keys($localesCurrency)))
                    $localeCurrency = $localeCurrencyConfig['default_currency'];

                // If there is no locale parameter in the route, switch to default locale en 
                if (empty($locale))
                    $locale = $localesConfig['default_lang'];
                if (empty($localeCurrency))
                    $localeCurrency = $localeCurrencyConfig['default_currency'];

                $translator = $sm->get('translator');
                $translator->setLocale($locale);
                $viewHelperManager = $sm->get('ViewHelperManager');
                $viewHelperManager->get("currencyFormat")->setCurrencyCode($localeCurrency); 
}, -10);

1 个答案:

答案 0 :(得分:0)

// Fetching JSON
$req_url = 'https://v6.exchangerate-api.com/v6/API_KEY/latest/USD';
$response_json = file_get_contents($req_url);
print_r($response_json);

// Continuing if we got a result
if(false !== $response_json) {

    // Try/catch for json_decode operation
    try {

        // Decoding
        $response = json_decode($response_json);

        // Check for success
        if('success' === $response->result) {

            // YOUR APPLICATION CODE HERE, e.g.
            $base_price = 10; // Your price in USD
            $EUR_price = round(($base_price * $response->conversion_rates->AUD), 2);
            echo"\n\n".$EUR_price;

        }

    }
    catch(Exception $e) {
        // Handle JSON parse error...
    }

}