Рекордсмен по количеству сообщений за 7 дней
Покинул форум
Сообщений всего: 2132
Дата рег-ции: Дек. 2008
Откуда: Москваль
Помог: 52 раз(а)
|
PHP:
скопировать код в буфер обмена
<?PHP function pr($str){ echo "<pre>"; echo "</pre><br/>"; } class Grabber{ private $money_url = ''; //откуда грабим курсы валют private $oil_url = 'http://news.yandex.ru/quotes/1006.xml'; //откуда грабим котировки нефти private $save_path = ''; //в каком файле все храним private $upd_dates = array(); //массив хранит даты последних обновлений private $courses = array(); //курсы валют private $oil = 0; //цена нефти public function __construct(){ $date_str = date('d/m/Y'); $this->money_url = 'http://www.cbr.ru/scripts/XML_daily.asp?date_req='.$date_str; $this->save_path = $_SERVER['DOCUMENT_ROOT'].'/money_grab/data.txt'; $this->load_file(); } public function get_oil(){ if(!isset($this->upd_dates['oil'])){ return false; } return array( 'date'=>$this->upd_dates['oil']['day'].'.'.$this->upd_dates['oil']['month'].'.'.$this->upd_dates['oil']['year'], 'value'=>$this->oil); } public function get_currency($type='EUR'){ if(!isset($this->courses[$type])){ return false; } return array( 'date'=>$this->upd_dates['money']['day'].'.'.$this->upd_dates['money']['month'].'.'.$this->upd_dates['money']['year'], 'value'=>$this->courses[$type]['value'], 'currency'=>$type, 'nominal'=>$this->courses[$type]['nominal']); } private function load_file(){ @$handle = fopen($this->save_path, "r"); if(!$handle){ $this->remake_file(); return false; } @flock($handle, LOCK_SH ); $buffer = ""; $buffer .= fgets($handle, 4096 ); } @flock ($handle, LOCK_UN ); $this->remake_file(); return false; } $this->remake_file(); return false; } if(isset($data['dates'])){ $this->upd_dates = $data['dates']; } if(isset($data['courses'])){ $this->courses = $data['courses']; } $this->oil = $data['oil']; } return true; } public function remake_file(){ $need2upd = false; if(isset($this->upd_dates['money'])){ $int_date_now = $this->date2int($this->upd_dates['money']); $new_data_money = $this->load_money(); $int_date_money_new = $this->date2int($new_data_money['update']); if($int_date_now !==false and $int_date_money_new !==false and $int_date_money_new > $int_date_now){ $need2upd = true; } } else{ $need2upd = true; $new_data_money = $this->load_money(); } if(isset($this->upd_dates['oil'])){ $int_date_now = $this->date2int($this->upd_dates['oil']); $new_data_oil = $this->load_oil(); $int_date_oil_new = $this->date2int($new_data_oil['update']); if($int_date_now !==false and $int_date_oil_new !==false and $int_date_oil_new > $int_date_now){ $need2upd = true; } } else{ $new_data_oil = $this->load_oil(); $need2upd = true; } if($need2upd){ $upd_content['dates'] = array(); $upd_content['dates']['money'] = $new_data_money['update']; $upd_content['dates']['oil'] = $new_data_oil['update']; $upd_content['courses'] = $new_data_money['data']; $upd_content['oil'] = $new_data_oil['data']; $this->upd_dates = $upd_content['dates']; $this->courses = $upd_content['courses']; $this->oil = $upd_content['oil']; $handle = fopen($this->save_path, "w"); @flock ($handle, LOCK_EX ); @flock ($handle, LOCK_UN ); } return true; } private function date2int ($date = array()){ return false; } if(!isset($date['year']) or !isset($date['month']) or !isset($date['day'])){ return false; } $int_val = $date['year']*365*24 + $date['month']*30*24 + $date['day']*24; if(isset($date['hour'])){ $int_val += $date['hour']; } return $int_val; } private function load_money(){ // $res = simplexml_load_file($this->money_url); $date_update = $res->xpath('/ValCurs/@Date'); $date_update = iconv('utf-8','windows-1251',$date_update[0 ]); if(preg_match("/^([0-9]{2})[\/\.]{1}([0-9]{2})[\/\.]{1}([0-9]{4})$/i", $date_update, $matches)){ $date['day'] = $matches[1]; $date['month'] = $matches[2]; $date['year'] = $matches[3]; } $return['update'] = $date; $list = $res->xpath('/ValCurs/Valute'); foreach($list as $valute){ $code = iconv('utf-8', 'windows-1251', $valute->CharCode); $valutes[$code] = array(); $valutes[$code]['nominal'] = iconv('utf-8', 'windows-1251', $valute->Nominal); $valutes[$code]['value'] = iconv('utf-8', 'windows-1251', $valute->Value); } $return['data'] = $valutes; return $return; } private function load_oil(){ // $res = simplexml_load_file($this->oil_url); $list = $res->xpath('/stock/sdt'); $needed = $list[0]; $date_update = iconv('utf-8','windows-1251',$needed['date']); if(preg_match("/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/i", $date_update, $matches)){ $date['day'] = $matches[3]; $date['month'] = $matches[2]; $date['year'] = $matches[1]; $date['hour'] = $matches[1]; } $time_update = iconv('utf-8','windows-1251',$needed['time']); $return['update'] = $date; $return['data'] = iconv('utf-8','windows-1251',$needed->value); return $return; } private function curl_load($url=''){ /* Пока прокси - оставим через курлы */ return $result; } } ?>
Написано под php5, есть версия и для 4-го (переделана обработка xml, некоторые моменты ООП)
Это не последняя версия (последнюю версию выложить не могу), тут придётся запускать remake_file для обновления кэша раз в сутки, немного оптимизировать
Пользоваться :
get_currency($type='EUR') - получить массив с датой последнего обновления и котировкой нужной валюты (В нашем случае EUR, есть USD, AUD и тд, полный список тут http://www.cbr.ru/scripts/XML_daily.asp?date_req=29/05/2009)
get_oil() - получить массив с датой последнего обновления и ценой на нефть
(Добавление)
ну и пример использования:
|