PHP class for getting the currency exchange rates from PrivatBank

Created - 02 Apr 2023

Here's the PHP class for getting the currency exchange rates from PrivatBank:


                class PrivatBankCurrency {
                  
                  private $apiUrl = 'https://api.privatbank.ua/p24api/pubinfo?exchange&json&coursid=11';
                  
                  public function getExchangeRate($currencyCode) {
                    $exchangeRates = json_decode(file_get_contents($this->apiUrl), true);
                    
                    foreach ($exchangeRates as $exchangeRate) {
                      if ($exchangeRate['ccy'] == $currencyCode) {
                        return $exchangeRate['buy'];
                      }
                    }
                    
                    return null; // if the exchange rate for the given currency is not found
                  }
                  
                }
    
                // Example usage of the class
                $privatBank = new PrivatBankCurrency();
                $usdExchangeRate = $privatBank->getExchangeRate('USD');
                echo "Exchange rate for USD: " . $usdExchangeRate;

The class contains a method getExchangeRate which takes a currency code (e.g. 'USD' for US dollar) and returns the buying exchange rate of that currency in Ukrainian hryvnia based on the data from PrivatBank. If the exchange rate for the given currency is not found, the method returns null.

To get the currency exchange rates, the class uses the PrivatBank API at the address https://api.privatbank.ua/p24api/pubinfo?exchange&json&coursid=11. The exchange rates are returned in JSON format, which is decoded using the json_decode function. Then the method searches for the exchange rate of the given currency in the array of exchange rates, and if it's found, the method returns the buying exchange rate of that currency in Ukrainian hryvnia.

All posts