php tcmb döviz kurları

tcmb.gov.tr den döviz kurları almak.

request method örneği

function getUrl($url, $method='', $vars='') {
    $ch = curl_init();
    //$header[] = "REMOTE_ADDR: 173.194.70.100"; //google ip adresi
    //$header[] = "HTTP_X_FORWARDED_FOR: 173.194.70.100"; //google ip adresi
    $header[] = "ACCEPT: ".$_SERVER['HTTP_ACCEPT'];

    if ($method == 'post') {
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);
    }
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
    curl_setopt($ch, CURLOPT_REFERER, $url);
    curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate');
    curl_setopt($ch, CURLOPT_AUTOREFERER, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    //curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,1);
    curl_setopt($ch, CURLOPT_SSLVERSION, 3);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
    curl_setopt($ch, CURLOPT_TIMEOUT, 120);
    //curl_setopt($ch, CURLOPT_COOKIEJAR, COOKIE);
    //curl_setopt($ch, CURLOPT_COOKIEFILE, COOKIE);
    $buffer = curl_exec($ch);
    curl_close($ch);
    return $buffer;
}

/**
 * usd ve euro tl bilgileri tcmb.gov.tr
 * @param string $CekilenKurlar
 * @return array
 */
function DovizKuruAl($CekilenKurlar='USD,EUR') {

    $istenenler = explode(',',$CekilenKurlar);
    $return = array();

    $XMLBugun = getUrl("http://www.tcmb.gov.tr/kurlar/today.xml");
    $BugunkuKurlar = simplexml_load_string($XMLBugun);
    $tmp = get_object_vars($BugunkuKurlar);
    $Currency = $tmp['Currency'];
    if(is_array($Currency)){
            foreach($Currency as $c){
                $b = get_object_vars($c);
                $b = array_values($b);
                if(!in_array($b[0]['CurrencyCode'],$istenenler)){
                    continue;
                }
                $return[$b[0]['CurrencyCode']] = array("durum"=>$b[1],"Alis"=>$b[4],"Satis"=>$b[5]);
            }
        }
    return $return;
}

Döviz kurlarını almak için

$kurlar = $this->DovizKuruAl();
print_r($kurlar); 

çıkti olarak

Array
(
    [USD] => Array
        (
            [durum] => 1
            [Alis] => 2.2358
            [Satis] => 2.2398
        )

    [EUR] => Array
        (
            [durum] => 1
            [Alis] => 2.7618
            [Satis] => 2.7668
        )

)

Farklı currency değeri almak

$kurlar = $this->DovizKuruAl('RUB');

octobercms için

<?php
/**
 * Created by PhpStorm.
 * User: ayhan
 * Date: 25.12.2018
 * Time: 14:26
 */

namespace ***\***\Classes;

use October\Rain\Exception\ApplicationException;
use October\Rain\Network\Http;

use Cache;
/**
 * Class Currencies
 * @package ***\***\Classes
 */
class Currencies
{

    protected $cacheStandbyTime = 1470; //24 hour 30 minute

    public $providers = [
        'tcmb' => [
            'url'=>'http://www.tcmb.gov.tr/kurlar/today.xml',
            'sourceType' => 'xml',
            'currency' => 'TRY',  //kurlar hangi para biriminde goruntuleniyor
            'crossCurrency' => 'USD', //kurlari hangi para birimine gore caprazlanacak jkm
            'parsing' => true,
            'parsingClass' => 'self',
            'parsingMethod' => 'tcmb',
            'request' => 'GET',
            'curlOptions' => [], //example: [ CURLOPT_SSL_VERIFYHOST => false, CURLOPT_SSL_VERIFYHOST => false ]
        ]
    ];

    protected $activeProvider = 'tcmb';

    /**
     * bizim ihtiyacimiz olan para birimleri, bu birimlerin degerleri ve capraz kurlari hesaplanacak
     * @var array
     */
    public $needCurrencies = [];

    /**
     * provider icin yapilan curl istegi sonucu
     * @var null
     */
    protected $rawSource = null;

    /**
     * provider icin degerlerin duzenlenmis  hesaplanabilir hali
     * @var array
     */
    public $allCurrencies = [];

    public
        $providerCurrency       = "",
        $providerCrossCurrency  = "",
        $defBuyValue            = 0,  //1 usd degeri cekilen kura gore nekadar
        $providerUrl            = "";

    /**
     * modul icin en son hali
     * @var array
     */
    public $sysCurrency = [];

    /**
     * yapilan cabraz kur degerlerine gore ibir para biriminin diğer para birimi tutarlari seklinde iki boyutlu array olarak tutar
     * @var array
     */
    public $crossCurrencies = [];

    public function __construct()
    {
        $this->prepareValues();
    }

    public function prepareValues()
    {
        $provider = $this->providers[$this->activeProvider];

        $this->providerCurrency         = $provider['currency'];
        $this->providerCrossCurrency    = $provider['crossCurrency'];
        $this->providerUrl              = $provider['url'];

        $this->needCurrencies = [
            'EUR', 'USD', 'RUB'
        ];
    }

    public function __get($name)
    {
        if(empty($this->allCurrencies) && in_array($name, ["rawSource", "allCurrencies", "sysCurrency", "crossCurrencies", "defBuyValue"]))
        {
            $this->get();
        }
        return $this->$name;
    }

    public function __call($name, $arguments)
    {
        if(property_exists($this, $name))
        {
            $this->__get($name);

            if(is_array($this->$name))
            {
                if(isset($arguments[0]) && !empty($this->$name[$arguments[0]]))
                {
                    $temp = $this->$name;
                    foreach ($arguments as $index)
                    {
                        if(empty($temp[$index]))
                        {
                            break;
                        }

                        $temp = $temp[$index];
                    }
                    return $temp;
                }
            }
            return $this->__get($name);
        }
        return "";
    }

    public function getAllCurrencies()
    {
        return $this->__get("allCurrencies"); //$this->allCurrencies;
    }

    public function getCrossCurrency()
    {
        return $this->__get("crossCurrencies"); //$this->crossCurrencies;
    }

    public function getSysCurrency()
    {
        return $this->__get("sysCurrency"); //$this->sysCurrency;
    }

    public function getRawSource()
    {
        return $this->__get("rawSource"); //$this->rawSource;
    }

    public function setProvider($providerName)
    {
        if(!empty($this->providerUrl[$providerName]))
        {
            $this->activeProvider = $providerName;
        }

        return $this;
    }

    public function get($cache = true)
    {
        $this->allCurrencies = [];
        $provider = $this->providers[$this->activeProvider];
        $cacheIndex = md5(json_encode($provider));

        if(!$cache)
        {
            Cache::forget($cacheIndex);
        }

        $this->rawSource = Cache::remember($cacheIndex, $this->cacheStandbyTime, function() use($provider){
                return Http::make($provider['url'], $provider['request'], function($http) use ($provider){
                    if(empty($provider['curlOptions']))
                    {
                        $http->timeout(2000);
                    }
                    else
                    {
                        if(is_array($provider['curlOptions']))
                        {
                            foreach ($provider['curlOptions'] as $optName=>$optValue)
                            {
                                $http->setOption($optName, $optValue);
                            }
                        }
                    }
                })->send()->body;
        });

        $this->rawParsing()
        ->crossRate();

        return $this;
    }

    protected function rawParsing($rawSource = false)
    {
        $provider = $this->providers[$this->activeProvider];
        $convert = false;

        if(!$rawSource)
        {
            $rawSource = $this->rawSource;
        }

        if($provider['parsing'])
        {
            $class  = $provider['parsingClass'];
            $method = $provider['parsingMethod'];

            $this->allCurrencies = call_user_func([$class, $method], $rawSource);
            $convert = true;
        }

        if(!$convert)
        {
            $this->allCurrencies = $rawSource;
        }

        return $this;
    }

    protected function crossRate()
    {
        if(empty($this->allCurrencies[$this->providerCrossCurrency]['buy']))
        {
            throw new ApplicationException(Message::trans("Kurlar cekilemedi")." #PARSEERROR");
        }

        $this->defBuyValue = $this->allCurrencies[$this->providerCrossCurrency]['buy'];

        $sysValues = [];

        foreach ($this->needCurrencies as $iso)
        {
            if(empty($this->allCurrencies[$iso]))
            {
                continue; //listede olmayan diger parabirimleri icin atla
            }

            if($iso == $this->providerCrossCurrency)
            {
                $sysValues[$iso] = 1;
                $sysValues[$this->providerCurrency] = $this->allCurrencies[$iso]['buy'];

                $this->crossCurrencies[$iso][$iso] = $sysValues[$iso];
                $this->crossCurrencies[$iso][$this->providerCurrency] = $sysValues[$this->providerCurrency];

                $this->crossCurrencies[$this->providerCurrency][$this->providerCrossCurrency] = (1/$sysValues[$this->providerCurrency]);
            }
            else
            {
                $sysValues[$iso] = ($this->defBuyValue / $this->allCurrencies[$iso]['buy']);

                $this->crossCurrencies[$this->providerCrossCurrency][$iso] = $sysValues[$iso];
            }

            foreach ($this->needCurrencies as $subiso)
            {
                if(empty($this->allCurrencies[$subiso])){ continue; }

                if($iso == $subiso)
                {
                    $sysValues[$iso.$subiso] = 1;
                    $this->crossCurrencies[$iso][$subiso] = $sysValues[$iso.$subiso];
                }
                elseif($subiso != $this->providerCrossCurrency)
                {
                    $def = $this->allCurrencies[$subiso]['buy'];
                    $sub = $this->allCurrencies[$iso]['buy'];

                    $sysValues[$subiso.$iso] = ($def / $sub);
                    $sysValues[$subiso.$this->providerCurrency] = $def; //proider varsayilan degeri

                    $this->crossCurrencies[$subiso][$iso] = $sysValues[$subiso.$iso];
                    $this->crossCurrencies[$subiso][$this->providerCurrency] = $def;

                    $this->crossCurrencies[$this->providerCurrency][$subiso] = (1/$def);
                }
            }
        }

        $this->crossCurrencies[$this->providerCurrency][$this->providerCurrency] = 1;
        $this->sysCurrency = $sysValues;
    }

    public function toGet($baseCurrency, $howCurrency)
    {
        if($baseCurrency == $this->providerCrossCurrency && $howCurrency == $this->providerCurrency)
        {
            return $this->allCurrencies[$baseCurrency]['buy'];
        }
        elseif($howCurrency == $this->providerCurrency)
        {
            $howCurrency = $this->providerCrossCurrency;
        }

        return ($this->allCurrencies[$baseCurrency]['buy'] / $this->allCurrencies[$howCurrency]['buy']);
    }

    ####################################################################################################################
    # PROVIDER METHODS
    ####################################################################################################################

    protected function tcmb()
    {
        $data = simplexml_load_string($this->rawSource);
        $json = json_encode($data);
        $array = json_decode($json, true);

        $temp = [];
        if(!empty($array['Currency']))
        {
            foreach ($array['Currency'] as $currency)
            {
                $iso    = trim(strtoupper($currency['@attributes']['CurrencyCode']));
                $buying = $currency['ForexBuying'];
                $selling = $currency['ForexSelling'];

                $temp[$iso] = ['buy' => floatval($buying), 'sell' => floatval($selling)];
            }
        }
        return $temp;
    }

}

Search Here