« Posts tagged 汇率

用php抓取汇率和libor

数据来源:中国资金管理网

功能:抓取前一交易日的libor和当天的汇率

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<?php
    //leon.nerr@gmail.com
    //2009-07-27
    header("Content-Type: text/html; charset=utf-8"); 
    function getArr($url,$date){
        $str = file_get_contents($url);
        $str = iconv('gb2312','utf8',$str);//
        //去html,js,css,iframe
        $str = preg_replace( "@<script(.*?)</script>@is", "", $str ); 
        $str = preg_replace( "@<iframe(.*?)</iframe>@is", "", $str ); 
        $str = preg_replace( "@<style(.*?)</style>@is", "", $str ); 
        $str = preg_replace( "@<(.*?)>@is", "", $str );
        $str = substr($str,strpos($str,$date),1000);
        if(strlen($str)>0){
            $arr = explode(' ',$str);
            foreach($arr as $key=>$value){
                if(strlen(trim($value))>0){
                    $result[] = trim($value);
                }   
            }    
        }
        return $result;
    }
    //
    if(date('N')==1){
        $yesterday = date('Y-m-d',strtotime("-3 days"));    
    }else{
        $yesterday = date('Y-m-d',strtotime("-1 days"));
    }
    $today = gmdate('Y-m-d');
    //
    $result = getArr("http://www.treasurer.org.cn/modules/wzjjgl/libor_index.php",$yesterday);
    if(is_array($result)){
        $libor['DATE'] = $result[0];
        $libor[1] = $result[6];
        $libor[3] = $result[10];
        $libor[6] = $result[16];
        $libor[12] = $result[28];
    }
    $result = getArr("http://www.treasurer.org.cn/",$today);
    if(is_array($result)){
        $rate['DATE']= $result[0];
        $rate['USD'] = $result[6];
        $rate['ERU'] = $result[12];  
    }
    //
    echo '<pre>';
    print_r($libor);
    print_r($rate);
    echo '<pre>';
?>

后来发现了一个叫snoopy的类,貌似很好用,有空一定要试一下

从Google读取当前人民币汇率中间价

PHP
<?php
    function findstr($line,$condi,$num){
        $a = strpos($line, $condi);
        $arr = explode(' ', substr($line, $a+$num, 20));
        return $arr[0];
    }
 
    $url = "http://www.google.com/search?&q=1usd%3D%3Frmb"; //usd
    $str = file_get_contents($url);
    preg_match_all("/1 U.S. dollar = .* Chinese yuan/", $str, $arr);
    $rate['usd'] = findstr($arr[0][0], '= ', 2);
 
    $url = "http://www.google.com/search?&q=1eur%3D%3Frmb"; //eur
    $str = file_get_contents($url);
    preg_match_all("/1 Euro = .* Chinese yuan/", $str, $arr);
    $rate['eur'] = findstr($arr[0][0], '= ', 2);
 
    print_r($rate);
?>