How to get official exchange rates for a given date in PHP. PHP script for loading exchange rates

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 website of the Central Bank. And in this article I will give the code PHP script for downloading exchange rates from the Central Bank website and display them on the page.

Here is the code for the script:

$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 the XML document into the DOM
$root = $dom->documentElement; // Get 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; // Get child nodes
for ($j = 0; $j< $childs_new->length; $j++) (
/* We are looking for the currencies we are interested in */
$el = $childs_new->item($j);
$code = $el->nodeValue;
if (($code == "USD") || ($code == "EUR")) $data = $childs_new; // Add the necessary currencies to the array
}
}
/* Loop through the array with currency data */
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."
";
}
}
?>

I tried to carefully comment on the code, so there should be no problems with understanding it. Also, in order to understand why there are so many and why such cycles, as well as where certain conditions come from, I strongly recommend that you follow the link from the code (just substitute the date). Then you will see XML Document, and it will be much easier for you to understand why such code was written.

There are many scripts on the Internet that show exchange rates. But I needed the dollar and euro from the central bank. I decided to look for scripts that will show official exchange rates on a given date. I came across an interesting jQuery article sorting a table. There in the script PHP exchange rate parser" An xml document is robbed using regular expressions. Regular expressions are heavily used in code robbery. The script works great, but has its own characteristics. It outputs a table in HTML with a large number of currencies. I need form 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 * xml document is parsed * */ 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 strtotime("+0 day") function allows you to change the time. Of course, how many zeros do not add anyway, the value of the variable will not change. I left this part of the code so that you can change the time at any time. I had to rearrange the array a bit. I used the $CharCode variable as the key for the array. There are many other arrays in my large array, and you can only access a certain array 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 Sterling
  4. AMD => Armenian dramas
  5. BYR => Belarusian ruble
  6. BGN => Bulgarian Lev
  7. BRL => Brazilian real
  8. HUF => Hungarian forint
  9. DKK => Danish krone
  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 krone
  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 => Turkmen new manat
  26. UZS => Uzbek sum
  27. UAH => Ukrainian hryvnia
  28. CZK => Czech Koruna
  29. SEK => Swedish krona
  30. CHF => Swiss franc
  31. ZAR => South African Rand
  32. KRW => Korean Won
  33. JPY => Japanese yen

I'm only interested in USD and EUR. I did not remove from

In some cases, when working with commerce, it becomes necessary 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 information on the exchange rate in XML format, it is a sin 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("Value")->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 the current one) and the cache lifetime, respectively. Since the Central Bank does not update currency data so often, you should not bother him just like that every time you use them. You can change the values ​​in these lines (optionally) to your own.

The usage of the function is as follows:

echo get_currency("USD", 3);

Here " USD” is a symbolic currency code (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 "character currency code - denomination and name":

AUD - 1 Australian dollar AZN - 1 Azerbaijani manat GBP - 1 British pound sterling AMD - 100 Armenian drams BYN - 1 Belarusian ruble BGN - 1 Bulgarian lev BRL - 1 Brazilian real HUF - 100 HUF HKD - 10 Hong Kong dollars DKK - 10 Danish krone USD - 1 US dollar EUR - 1 euro INR - 100 Indian rupees KZT - 100 Kazakhstan tenge CAD - 1 Canadian dollar KGS - 100 Kyrgyz soms CNY - 10 Chinese yuan MDL - 10 MDL NOK - 10 Norwegian kroner PLN - 1 Polish PLN 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 som UAH - 10 Ukrainian hryvnia CZK - 10 CZK SEK - 10 SEK CHF - 1 Swiss franc ZAR - 10 South African rand KRW - 1,000 ROK won

I hope the function finds its place in your project. If you have any questions or something seemed incomprehensible - be sure to write about it in the comments under this article.

In some cases, when working with commerce, it becomes necessary 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 information on the exchange rate in XML format, it is a sin 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("Value")->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 the current one) and the cache lifetime, respectively. Since the Central Bank does not update currency data so often, you should not bother him just like that every time you use them. You can change the values ​​in these lines (optionally) to your own.

The usage of the function is as follows:

echo get_currency("USD", 3);

Here " USD” is a symbolic currency code (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 "character currency code - denomination and name":

AUD - 1 Australian dollar AZN - 1 Azerbaijani manat GBP - 1 British pound sterling AMD - 100 Armenian drams BYN - 1 Belarusian ruble BGN - 1 Bulgarian lev BRL - 1 Brazilian real HUF - 100 HUF HKD - 10 Hong Kong dollars DKK - 10 Danish krone USD - 1 US dollar EUR - 1 euro INR - 100 Indian rupees KZT - 100 Kazakhstan tenge CAD - 1 Canadian dollar KGS - 100 Kyrgyz soms CNY - 10 Chinese yuan MDL - 10 MDL NOK - 10 Norwegian kroner PLN - 1 Polish PLN 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 som UAH - 10 Ukrainian hryvnia CZK - 10 CZK SEK - 10 SEK CHF - 1 Swiss franc ZAR - 10 South African rand KRW - 1,000 ROK won

I hope the function finds its place in your project. If you have any questions or something seemed incomprehensible - be sure to write about it in the comments under this article.

Good afternoon dear friends. As you know, recently (February 11) another devaluation took place in Kazakhstan, this "Black Tuesday" as it was called by many on the Internet, hit the pockets of many. I will not write another negative article on this topic. I don't think it's necessary. What is done is done. But on that ill-fated day, I was very much outraged by the fact that nowhere on the Internet it was possible to find out the exact rate of the dollar, euro or other foreign currency. All known and unknown (hello google) sites were not available 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, the sites did not work.

And in the evening, when my passions about devaluation began to subside and my nerves began to calm down, I decided that I needed to write myself a small exchange rate informer on my cozy little blog. As I said above, I did not want to use the widgets of other sites, since these sites were "lying" when the whole kaznet wanted to know this damn exchange rate. :) Below is the php informer script, 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 into which you want to convert, as well as increase or change arrays $from[?], add other currencies, just don't forget to change the loop condition if you have increased the number of withdrawn currencies. You can get the identifier (name) of currencies from the link - https://www.google.com/finance/converter. As you probably understood, the script parses this google page in a loop and takes the information it needs.

How to install this script on your site? 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 there is a problem, 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 email me and I will try to help you. I hope this article was helpful to you. :)

P.S: For myself, I slightly optimized the script (added caching) and gave the cron task to update the script once an hour. My version saves the * .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."
";
}

// save captured output to .html file
file_put_contents("currency.html", ob_get_contents());
// end buffering and display 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 clog the site. After that, you will need to add a task in the cron, access the script every n hours. And once through the browser, manually access script so that it creates an html file, which we will refer to in the future.Next, you can display the script in widgets through the 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 kind of output 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 access google. You can implement caching differently and check by date so as not to use cron. But personally, I proceeded from a simple one. I don’t like to be smart. :)

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

Professionals from all parts of the city



What else to read