Skip to content

Instantly share code, notes, and snippets.

@barisesen
Last active May 29, 2018 07:53
Show Gist options
  • Save barisesen/f07c0c23e72c30654b115b951fef0909 to your computer and use it in GitHub Desktop.
Save barisesen/f07c0c23e72c30654b115b951fef0909 to your computer and use it in GitHub Desktop.
Geriye dönük olarak dolar kurunu TCMB sitesinden parse eder.
<?php
/* @barisesen
* http://www.tcmb.gov.tr/kurlar/201805/25052018.xml
*/
public function oldExchangeRate($date)
{
$dt = Carbon::parse($date);
if ($dt->isWeekend()) {
return $this->oldExchangeRate($dt->subDay());
}
$year = $dt->year;
$month = $dt->month < 10 ? "0{$dt->month}" : $dt->month;
$day = $dt->day < 10 ? "0{$dt->day}" : $dt->day;
if (Cache::store('redis')->has("{$year}{$month}{$day}_USD")) {
return Cache::store('redis')->get("{$year}{$month}{$day}_USD");
}
try {
$site = $this->request("http://www.tcmb.gov.tr/kurlar/{$year}{$month}/{$day}{$month}{$year}.xml");
$data = simplexml_load_string($site);
$dolar = ['selling' => (string)$data->Currency[0]->ForexSelling[0], 'date' => (string) Carbon::now()];
Cache::store('redis')->put("{$year}{$month}{$day}_USD", $dolar , 24 * 60);
return $dolar;
} catch (Exception $e) {
// resmi tatil günlerinde kayıt olmadığı için hata döner. Bu durumda bir önceki günün kuruna bakabiliriz.
return $this->oldExchangeRate($dt->subDay());
}
}
<?php
public function request($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_REFERER, 'http://www.google.com');
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
if (curl_error($ch)) {
throw new Exception("{$url} adresinden doviz kuru alinamadi!");
}
curl_close($ch);
return $response;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment