Php getting exchange rates. How to get official exchange rates for a given date in PHP

In some cases, when working with commerce, there is a need to obtain up-to-date information about the exchange rate of a particular currency. The Central Bank is the best source of such data, and given that it provides open and timely updated information on exchange rates in XML format, it would be a shame not to use it.

This function looks like this:

Function get_currency($currency_code, $format) ( $date = date("d/m/Y"); // Current date $cache_time_out = "3600"; // Cache lifetime in seconds $file_currency_cache = __DIR__."/XML_daily .asp"; if(!is_file($file_currency_cache) || filemtime($file_currency_cache)< (time() - $cache_time_out)) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "https://www.cbr.ru/scripts/XML_daily.asp?date_req=".$date); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HEADER, 0); $out = curl_exec($ch); curl_close($ch); file_put_contents($file_currency_cache, $out); } $content_currency = simplexml_load_file($file_currency_cache); return number_format(str_replace(",", ".", $content_currency->xpath("Valute")->Value), $format); )

It contains the lines:

$date = date("d/m/Y"); // Current date $cache_time_out = "3600"; // Cache lifetime in seconds

are responsible for the date (in our case it is current) and the cache lifetime, respectively. Since the Central Bank does not update data on currencies very often, you should not just pester it every time you use them. You can change the values ​​in these lines (if desired) to your own.

The usage of the function is as follows:

Echo get_currency("USD", 3);

Here " USD" is the symbolic code of the currency (in our case, it is the US dollar), and " 3 " - a number of simbols after comma.

Acceptable list of currencies provided by the Central Bank of the Russian Federation (at the time of writing) in the form of “currency symbol code - denomination and name”:

AUD – 1 Australian dollar AZN – 1 Azerbaijani manat GBP – 1 UK pound AMD – 100 Armenian dram BYN – 1 Belarusian ruble BGN – 1 Bulgarian lev BRL – 1 Brazilian real HUF – 100 Hungarian forints HKD – 10 Hong Kong dollars DKK – 10 Danish kroner USD – 1 US dollar EUR – 1 euro INR – 100 Indian rupees KZT – 100 Kazakhstani tenge CAD – 1 Canadian dollar KGS – 100 Kyrgyz som CNY – 10 Chinese yuan MDL – 10 Moldovan lei NOK – 10 Norwegian kroner PLN – 1 Polish zloty RON – 1 Romanian leu XDR – 1 SDR (special drawing rights) SGD – 1 Singapore dollar TJS – 10 Tajik somoni TRY – 1 Turkish lira TMT – 1 new Turkmen manat UZS – 10,000 Uzbek soums UAH – 10 Ukrainian hryvnia CZK – 10 Czech crowns SEK - 10 Swedish crowns CHF - 1 Swiss franc ZAR - 10 South African rands KRW - 1,000 Korean won

I hope the feature finds its place in your project. If you have any questions or something seems unclear, be sure to write about it in the comments under this article.

In some cases, when working with commerce, there is a need to obtain up-to-date information about the exchange rate of a particular currency. The Central Bank is the best source of such data, and given that it provides open and timely updated information on exchange rates in XML format, it would be a shame not to use it.

This function looks like this:

Function get_currency($currency_code, $format) ( $date = date("d/m/Y"); // Current date $cache_time_out = "3600"; // Cache lifetime in seconds $file_currency_cache = __DIR__."/XML_daily .asp"; if(!is_file($file_currency_cache) || filemtime($file_currency_cache)< (time() - $cache_time_out)) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "https://www.cbr.ru/scripts/XML_daily.asp?date_req=".$date); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HEADER, 0); $out = curl_exec($ch); curl_close($ch); file_put_contents($file_currency_cache, $out); } $content_currency = simplexml_load_file($file_currency_cache); return number_format(str_replace(",", ".", $content_currency->xpath("Valute")->Value), $format); )

It contains the lines:

$date = date("d/m/Y"); // Current date $cache_time_out = "3600"; // Cache lifetime in seconds

are responsible for the date (in our case it is current) and the cache lifetime, respectively. Since the Central Bank does not update data on currencies very often, you should not just pester it every time you use them. You can change the values ​​in these lines (if desired) to your own.

The usage of the function is as follows:

Echo get_currency("USD", 3);

Here " USD" is the symbolic code of the currency (in our case, it is the US dollar), and " 3 " - a number of simbols after comma.

Acceptable list of currencies provided by the Central Bank of the Russian Federation (at the time of writing) in the form of “currency symbol code - denomination and name”:

AUD – 1 Australian dollar AZN – 1 Azerbaijani manat GBP – 1 UK pound AMD – 100 Armenian dram BYN – 1 Belarusian ruble BGN – 1 Bulgarian lev BRL – 1 Brazilian real HUF – 100 Hungarian forints HKD – 10 Hong Kong dollars DKK – 10 Danish kroner USD – 1 US dollar EUR – 1 euro INR – 100 Indian rupees KZT – 100 Kazakhstani tenge CAD – 1 Canadian dollar KGS – 100 Kyrgyz som CNY – 10 Chinese yuan MDL – 10 Moldovan lei NOK – 10 Norwegian kroner PLN – 1 Polish zloty RON – 1 Romanian leu XDR – 1 SDR (special drawing rights) SGD – 1 Singapore dollar TJS – 10 Tajik somoni TRY – 1 Turkish lira TMT – 1 new Turkmen manat UZS – 10,000 Uzbek soums UAH – 10 Ukrainian hryvnia CZK – 10 Czech crowns SEK - 10 Swedish crowns CHF - 1 Swiss franc ZAR - 10 South African rands KRW - 1,000 Korean won

I hope the feature finds its place in your project. If you have any questions or something seems unclear, be sure to write about it in the comments under this article.

Many of you have repeatedly seen that some sites display exchange rates. Of course, the administrators of these sites themselves do not change them daily (I hope). They download them from the Central Bank website. And in this article I will give the code PHP script for downloading currency rates from the Central Bank website and displaying them on the page.

Here's the script code right away:

$date = date("d/m/Y"); // Today's date in the required format
$link = "http://www.cbr.ru/scripts/XML_daily.asp?date_req=$date"; // Link to XML file with exchange rates
$content = file_get_contents($link); // Download page content
$dom = new domDocument("1.0", "cp1251"); // Create DOM
$dom->loadXML($content); // Load an XML document into the DOM
$root = $dom->documentElement; // Take the root element
$childs = $root->childNodes; // Get a list of child elements
$data = array(); // Data set
for ($i = 0; $i< $childs->length; $i++) (
$childs_new = $childs->item($i)->childNodes; // Take child nodes
for ($j = 0; $j< $childs_new->length; $j++) (
/* We are looking for currencies that interest us */
$el = $childs_new->item($j);
$code = $el->nodeValue;
if (($code == "USD") || ($code == "EUR")) $data = $childs_new; // Add the required currencies to the array
}
}
/* Iterate through an array with data on currencies */
for ($i = 0; $i< count($data); $i++) {
$list = $data[$i];
for ($j = 0; $j< $list->length; $j++) (
$el = $list->item($j);
/* Display exchange rates */
if ($el->nodeName == "Name") echo $el->nodeValue." - ";
elseif ($el->nodeName == "Value") echo $el->nodeValue." rubles
";
}
}
?>

I tried to comment the code thoroughly, so there shouldn’t be any problems understanding it. Also, in order to understand why there are so many and why exactly such cycles, as well as where certain conditions come from, I strongly recommend visiting the link from the code (just insert the date). Then you will see XML document, and it will be much easier for you to understand why this particular code was written.

There are many scripts on the Internet that show exchange rates. But I needed the dollar and euro exchange rate from central bank. I decided to look for scripts that will show official courses currencies for a given date. I came across an interesting article jQuery table sorting. There in the script" PHP currency rate parser" An xml document is robbed using regular expressions. Regular expressions are actively used in code burglary. The script works great, but has its own peculiarities. It displays a table in HTML with a large number of currencies. I need generate a JSON array from a table with exchange rates. This array is like a sausage. This is what programmers call such an array. There are very large sausages in large quantities)))

/* * getArr() * exchange rates from the central bank * parsing the xml document * */ function getArr() ( $url = "http://www.cbr.ru/scripts/XML_daily.asp?date_req=". date("d/m/Y",strtotime("+0 day")); $cbr_xml = str_replace(array("\n","\r","\t"),"",getContentPage($url )); if(preg_match_all("~ (.*?) ~i",$cbr_xml,$Valute)) ( foreach($Valute as $data) ( preg_match("~ (.*?) ~i",$data ,$CharCode); preg_match("~ (.*?) ~i",$data,$NumCode); $arr[$CharCode]["num_code"].= $NumCode; preg_match("~ (.*?) ~i",$data,$Nominal); $arr[$CharCode]["nominal"] = $Nominal; preg_match("~ (.*?) ~i",$data,$Name); $arr[$ CharCode]["name"].= toUtf8($Name); preg_match("~ (.*?) ~i",$data,$Value); $arr[$CharCode]["value"].= $Value ; $i++; ) return $arr; ) ) function getContentPage($url) ( $c = curl_init($url); curl_setopt($c, CURLOPT_RETURNTRANSFER, 1); curl_setopt($c, CURLOPT_FOLLOWLOCATION, 1); $text = curl_exec($c); curl_close($c); return $text; ) //encode to Utf8 function toUtf8($str) ( return mb_convert_encoding($str, "utf-8", "windows-1251"); ) $arr = getArr(); echo json_encode($arr); /* ( "EUR":("num_code":"978", "nominal":"1", "name":"\u0415\u0432\u0440\u043e", "value":"63.6090"), "USD":("num_code":"840", "nominal":"1", "name":"\u0414\u043e\u043b\u043b\u0430\u0440 \u0421\u0428\u0410", "value": "58.0374") )*/

You can view both today's exchange rate and yesterday's exchange rate. The function strtotime("+0 day") allows you to change the time. Of course, no matter how many zeros you add, the value of the variable will not change. I left this part of the code so that the time can be changed at any time. I had to redo the array a little. I used the $CharCode variable as the key for the array. In my large array there are many other arrays and you can access a specific array only by key (EUR). In my case, the $CharCode variable takes the following values:

  1. AUD => Australian dollar
  2. AZN => Azerbaijani manat
  3. GBP => British Pound
  4. AMD => Armenian dramas
  5. BYR => Belarusian rubles
  6. BGN => Bulgarian Lev
  7. BRL => Brazilian Real
  8. HUF => Hungarian forint
  9. DKK => Danish kroner
  10. USD => US Dollar
  11. EUR => Euro
  12. INR => Indian Rupees
  13. KZT => Kazakhstan tenge
  14. CAD => Canadian dollar
  15. KGS => Kyrgyzstani som
  16. CNY => Chinese Yuan
  17. MDL => Moldovan lei
  18. NOK => Norwegian kroner
  19. PLN => Polish zloty
  20. RON => Romanian New Leu
  21. XDR => SDR (Special Drawing Rights)
  22. SGD => Singapore dollar
  23. TJS => Tajikistani somoni
  24. TRY => Turkish lira
  25. TMT => New Turkmen manat
  26. UZS => Uzbek som
  27. UAH => Ukrainian hryvnia
  28. CZK => Czech crowns
  29. SEK => Swedish krona
  30. CHF => Swiss franc
  31. ZAR => South African Rand
  32. KRW => Republic of Korea Won
  33. JPY => Japanese Yen

I'm only interested in USD and EUR. I didn't delete it from

Good afternoon dear friends. As you know, recently (February 11) we had another devaluation in Kazakhstan, this “Black Tuesday”, as many on the Internet called it, hit the pockets of many. I will not write another negative article on this topic. I don't think this is necessary. What is done is done. But on that ill-fated day I was very outraged by the fact that nowhere on the Internet was it possible to find out the exact exchange rate of the dollar, euro or other foreign currency. All known and unknown (hello Google) sites were not accessible to me. Perhaps some sites fell out of favor with Kazakhstani users and were not ready for such a load of users. But the fact remains that the sites did not work.

And in the evening, when my passions about devaluation began to subside and my nerves began to return to their calm state, I decided that I needed to write myself a small exchange rate informer for my cozy little blog. As I said above, I didn’t want to use the widgets of other sites, since these sites were “lying” when the whole government wanted to know this damn exchange rate. :) Below is the informer script in PHP, I think the script does not need comments:

$amount = "1";
$from = "USD";
$from = "EUR";
$from = "RUB";
$to= "KZT";
$i=0;
while($i<= 2){
$i++;
$get = explode(" ",$get);
$get = explode("
",$get);


";
}
?>

The script is universal, you can change the variable $to to another currency you want to convert to, as well as increase or change arrays $from[?], add other currencies, just remember to change the loop condition if you have increased the number of currencies being output. You can get the identifier (name) of currencies using the link - https://www.google.com/finance/converter. As you probably understand, the script parses this Google page in a loop and takes the information it needs.

How to install this script on your website? If you have a wordpress engine, you will need to install the plugin" PHP Code Widget" and select this widget and add all the code there. This is the easiest way. If a problem arises, you can always disable the plugin and everything will return as it was. I don’t offer complex options for installing the script. You can write to me by email, and I will try to help you. I hope this article was useful to you. :)

P.S: For myself, I optimized the script a little (added caching) and gave the cron task to update the script once an hour. My version saves a *.html file and I display it in widgets via ajax.

// Start output buffering
ob_start();

$amount = "1";
$from = "USD";
$from = "EUR";
$from = "RUB";
$to= "KZT";
$i=0;
while($i<= 2){
$i++;
$get = file_get_contents("https://www.google.com/finance/converter?a=$amount&from=$from[$i]&to=$to");
$get = explode(" ",$get);
$get = explode("
",$get);
$converted_amount = preg_replace("/[^0-9\.]/", null, $get);
$converted_amount = round($converted_amount,2);
echo $amount." ".$from[$i]." = ".$converted_amount." ".$to."
";
}

// saving captured output to .html file
file_put_contents("currency.html", ob_get_contents());
// end buffering and displaying page
ob_end_flush();
?>

Save the script in *.php format, it is advisable to save it in a separate folder (for example, in the “scripts” folder, so as not to clutter the site. After that, you will need to add a task in the crown, access the script once n hours. And once through the browser manually access script so that it creates an html file, which we will refer to later.Next, you can display the script in widgets through an iframe:

‹script›
function show_temp()
{
$.ajax((
url: "http://yoursite/scripts/currency.html",
cache: false,
success: function(html)(
$("#currency").html(html);
}
});
}
$(document).ready(function())(
show_temp();
});

This output method will allow you to change the font size, font color or add any other effects via CSS (Cascading Style Sheet).

An optimized version of the script will not load the server and constantly contact Google. You can implement caching differently, and check by date, so as not to use cron. But personally, I proceeded from the simple. I don’t like to split hairs. :)

Is your washing machine broken? 1v.kz will help! - Repair of washing machines in Almaty:

Specialists from all areas of the city

Share