Warning: Cannot use a scalar value as an array in /home/admin/public_html/forum/include/fm.class.php on line 757

Warning: Invalid argument supplied for foreach() in /home/admin/public_html/forum/include/fm.class.php on line 770
Форумы портала PHP.SU :: Версия для печати :: Грабим курсы валют и котировки нефти
Форумы портала PHP.SU » PHP » Пользовательские функции » Грабим курсы валют и котировки нефти

Страниц (1): [1]
 

1. Stierus - 29 Мая, 2009 - 12:31:59 - перейти к сообщению
PHP:
скопировать код в буфер обмена
  1. <?PHP
  2.  
  3. function pr($str){
  4.         echo "<pre>";
  5.         var_export($str);
  6.         echo "</pre><br/>";
  7. }
  8.  
  9. class Grabber{
  10.         private $money_url = ''; //откуда грабим курсы валют
  11.         private $oil_url = 'http://news.yandex.ru/quotes/1006.xml'; //откуда грабим котировки нефти
  12.         private $save_path = ''; //в каком файле все храним
  13.         private $upd_dates = array(); //массив хранит даты последних обновлений
  14.         private $courses = array(); //курсы валют
  15.         private $oil = 0; //цена нефти
  16.        
  17.        
  18.        
  19.         public function __construct(){
  20.                 $date_str = date('d/m/Y');
  21.                 $this->money_url = 'http://www.cbr.ru/scripts/XML_daily.asp?date_req='.$date_str;
  22.                 $this->save_path = $_SERVER['DOCUMENT_ROOT'].'/money_grab/data.txt';
  23.                 $this->load_file();
  24.         }
  25.        
  26.         public function get_oil(){
  27.                 if(!isset($this->upd_dates['oil'])){
  28.                         return false;
  29.                 }
  30.                 return array(   'date'=>$this->upd_dates['oil']['day'].'.'.$this->upd_dates['oil']['month'].'.'.$this->upd_dates['oil']['year'],
  31.                                                 'value'=>$this->oil);
  32.         }
  33.        
  34.         public function get_currency($type='EUR'){
  35.                 if(!isset($this->courses[$type])){
  36.                         return false;
  37.                 }
  38.                 return array(   'date'=>$this->upd_dates['money']['day'].'.'.$this->upd_dates['money']['month'].'.'.$this->upd_dates['money']['year'],
  39.                                                 'value'=>$this->courses[$type]['value'],
  40.                                                 'currency'=>$type,
  41.                                                 'nominal'=>$this->courses[$type]['nominal']);
  42.         }
  43.        
  44.         private function load_file(){
  45.                 @$handle = fopen($this->save_path, "r");
  46.                 if(!$handle){
  47.                         $this->remake_file();
  48.                         return false;
  49.                 }
  50.  
  51.                 @flock($handle, LOCK_SH);
  52.                 $buffer = "";
  53.                 while (!feof($handle)) {
  54.                         $buffer .= fgets($handle, 4096);
  55.                 }
  56.                 @flock ($handle, LOCK_UN);
  57.                 fclose($handle);
  58.                 if(strlen($buffer) < 5){
  59.                         $this->remake_file();
  60.                         return false;
  61.                 }
  62.                
  63.                 @$data = unserialize($buffer);
  64.                 if(!is_array($data)){
  65.                         $this->remake_file();
  66.                         return false;
  67.                 }
  68.                
  69.                 if(isset($data['dates'])){
  70.                         $this->upd_dates = $data['dates'];
  71.                 }
  72.                 if(isset($data['courses'])){
  73.                         $this->courses = $data['courses'];
  74.                 }
  75.                 if(isset($data['oil'])){
  76.                         $this->oil = $data['oil'];
  77.                 }
  78.                 return true;
  79.         }
  80.        
  81.         public function remake_file(){
  82.                 $need2upd = false;
  83.                 $upd_content = array();
  84.  
  85.                 if(isset($this->upd_dates['money'])){
  86.                         $int_date_now = $this->date2int($this->upd_dates['money']);
  87.                         $new_data_money = $this->load_money();
  88.                         $int_date_money_new = $this->date2int($new_data_money['update']);
  89.                         if($int_date_now !==false and $int_date_money_new !==false and $int_date_money_new > $int_date_now){
  90.                                 $need2upd = true;
  91.                         }
  92.                 }
  93.                 else{
  94.                         $need2upd = true;
  95.                         $new_data_money = $this->load_money();
  96.                 }
  97.                
  98.                 if(isset($this->upd_dates['oil'])){
  99.                         $int_date_now = $this->date2int($this->upd_dates['oil']);
  100.                         $new_data_oil = $this->load_oil();
  101.                         $int_date_oil_new = $this->date2int($new_data_oil['update']);
  102.                         if($int_date_now !==false and $int_date_oil_new !==false and $int_date_oil_new > $int_date_now){
  103.                                 $need2upd = true;
  104.                         }
  105.                 }
  106.                 else{
  107.                         $new_data_oil = $this->load_oil();
  108.                         $need2upd = true;
  109.                 }
  110.                
  111.                 if($need2upd){
  112.                        
  113.                         $upd_content['dates'] = array();
  114.                         $upd_content['dates']['money'] = $new_data_money['update'];
  115.                         $upd_content['dates']['oil'] = $new_data_oil['update'];
  116.                         $upd_content['courses'] = $new_data_money['data'];
  117.                         $upd_content['oil'] = $new_data_oil['data'];
  118.                         $this->upd_dates = $upd_content['dates'];
  119.                         $this->courses = $upd_content['courses'];
  120.                         $this->oil = $upd_content['oil'];
  121.                        
  122.                         $data = serialize($upd_content);
  123.        
  124.                         $handle = fopen($this->save_path, "w");
  125.                         @flock ($handle, LOCK_EX);
  126.                         fwrite ($handle, $data);
  127.                         @flock ($handle, LOCK_UN);
  128.                         fclose($handle);
  129.                 }
  130.                 return true;
  131.         }
  132.        
  133.         private function date2int($date = array()){
  134.                 if(!is_array($date)){
  135.                         return false;
  136.                 }
  137.                 if(!isset($date['year']) or !isset($date['month']) or !isset($date['day'])){
  138.                         return false;
  139.                 }
  140.                 $int_val = $date['year']*365*24 + $date['month']*30*24 + $date['day']*24;
  141.                 if(isset($date['hour'])){
  142.                         $int_val += $date['hour'];
  143.                 }
  144.                 return $int_val;
  145.         }
  146.        
  147.         private function load_money(){
  148. //              $res = simplexml_load_file($this->money_url);
  149.                 $res = simplexml_load_string($this->curl_load($this->money_url));
  150.                 $date_update = $res->xpath('/ValCurs/@Date');
  151.                 $date_update = iconv('utf-8','windows-1251',$date_update[0]);
  152.                 if(preg_match("/^([0-9]{2})[\/\.]{1}([0-9]{2})[\/\.]{1}([0-9]{4})$/i", $date_update, $matches)){
  153.                         $date = array();
  154.                         $date['day'] = $matches[1];
  155.                         $date['month'] = $matches[2];
  156.                         $date['year'] = $matches[3];
  157.                 }
  158.                 $return = array();
  159.                 $return['update'] = $date;
  160.                 $list = $res->xpath('/ValCurs/Valute');
  161.                 $valutes = array();
  162.                 foreach($list as $valute){
  163.                         $code = iconv('utf-8', 'windows-1251', $valute->CharCode);
  164.                         $valutes[$code] = array();
  165.                         $valutes[$code]['nominal'] = iconv('utf-8', 'windows-1251', $valute->Nominal);
  166.                         $valutes[$code]['value'] = iconv('utf-8', 'windows-1251', $valute->Value);
  167.                 }
  168.                 $return['data'] = $valutes;
  169.                 return $return;
  170.         }
  171.        
  172.         private function load_oil(){
  173. //              $res = simplexml_load_file($this->oil_url);
  174.                 $res = simplexml_load_string($this->curl_load($this->oil_url));
  175.                 $list = $res->xpath('/stock/sdt');
  176.                 $needed = $list[0];
  177.                
  178.                 $date_update = iconv('utf-8','windows-1251',$needed['date']);
  179.                 if(preg_match("/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/i", $date_update, $matches)){
  180.                         $date = array();
  181.                         $date['day'] = $matches[3];
  182.                         $date['month'] = $matches[2];
  183.                         $date['year'] = $matches[1];
  184.                         $date['hour'] = $matches[1];
  185.                 }
  186.                 $time_update = iconv('utf-8','windows-1251',$needed['time']);
  187.                 $date['hour'] = intval(substr($time_update, 0, 2));
  188.                 $return = array();
  189.                 $return['update'] = $date;
  190.                 $return['data'] = iconv('utf-8','windows-1251',$needed->value);
  191.                 return $return;
  192.         }
  193.        
  194.         private function curl_load($url=''){
  195.                 /* Пока прокси - оставим через курлы */
  196.                 $ch = curl_init();
  197.                 curl_setopt($ch, CURLOPT_URL, $url);
  198.                 curl_setopt($ch, CURLOPT_HEADER, 0);
  199.                 curl_setopt($ch, CURLOPT_TIMEOUT, 5);
  200.                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  201.                 $result = curl_exec($ch);
  202.                 curl_close($ch);
  203.                 return $result;
  204.         }
  205.        
  206. }
  207. ?>


Написано под 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() - получить массив с датой последнего обновления и ценой на нефть
(Добавление)
ну и пример использования:
PHP:
скопировать код в буфер обмена
  1. <?PHP
  2. include('class.php');
  3. $test = new Grabber();
  4. pr($test->get_currency());
  5. ?>
2. Фетильник - 08 Июня, 2009 - 12:11:25 - перейти к сообщению
Спасибо. Обязательно воспользуюсь
3. 563434 - 01 Августа, 2009 - 21:36:47 - перейти к сообщению
А грабером курсов нефти под php4 поделитесь?

 

Powered by ExBB FM 1.0 RC1