Get currency rates from ECB

For a WooCommerce powered site I needed a currency rate fetching function so here is what I used.

/**
 * Get currency rate
 *
 * Info @ http://www.ecb.int/stats/exchange/eurofxref/html/index.en.html
 * The reference rates are usually updated by 3 pm CET
 * cron: 0 17 * * 1,2,3,4,5
 *
 * @param   string  Currency code name
 * @return  float
 **/
function wi_get_currency_rate( $currency = 'CZK' ) {

    if ( false === ( $currencies = get_transient( 'wi_currency_rates' ) ) ) {

        $currencies = array();
        $xml = wp_remote_get( 'http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml',
            array( 'user-agent' => 'WordPress' )
        );

        $xml = simplexml_load_string( $xml['body'] );
        foreach( $xml->Cube->Cube->Cube as $cube )
            $currencies[ $cube->attributes()->currency ] = (float) $cube->attributes()->rate;

        set_transient( 'wi_currency_rates', $currencies, 23 * HOUR_IN_SECONDS );
    }


    return $currencies[ $currency ];

}
Advertisements

About Michal Zuber

Full stack developer, biker and rollerblader. Owner and developer at https://nevilleweb.sk/ Co-founded http://neville.sk/ Blog at https://michalzuber.wordpress.com/
This entry was posted in php, woocommerce, wordpress and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s