PHP如何获取货币汇率?

2025-11-09 08:19:57

1、编写输入页面;

//demo.html

<html><head>    <meta charset="utf-8">    <title>获取汇率</title></head><body style="margin-bottom: 10px;">   基本货币:<input  type="text" id="basicCoin" name="basicCoin"/>==>   <input  type="text" id="changeCoin" name="changeCoin"/>   <input  type="button" id="btn" name="btn" value="提交" onclick="req_server()"/>    <P id="result">    <script>    function req_server(){          //获取基本货币        var basicCoin=document.getElementById("basicCoin").value;        //获取兑换货币        var changeCoin=document.getElementById("changeCoin").value;                var xmlhttp;         //创建XMLHttpRequest对象          if (window.XMLHttpRequest){             xmlhttp=new XMLHttpRequest();          }else{              xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");          }                    //设置请求类型,请求地址        xmlhttp.open("GET","deal.php?basicCoin="+basicCoin+"&changeCoin="+changeCoin,true);          //发送请求至服务器          xmlhttp.send();          //处理onreadystatechange事件          xmlhttp.onreadystatechange=function()          {              //结果处理            if (xmlhttp.readyState==4 && xmlhttp.status==200){                  var data= eval("("+xmlhttp.responseText+")");                alert(data.status);                if(data.status=="ok"){                    document.getElementById("result").innerHTML="兑换汇率为:"+data.ret;                }else{                    document.getElementById("result").innerHTML="处理错误!请检查!";                }            }          }                }    </script></body></html>    

PHP如何获取货币汇率?

PHP如何获取货币汇率?

2、运行效果:

PHP如何获取货币汇率?

3、php后台处理:

<?php    //获取参数    $basicCoin = $_GET['basicCoin'];    $changeCoin = $_GET['changeCoin'];    $result = json_encode(array("status"=>"err","ret"=>0));    if($basicCoin && $changeCoin){        $str=$basicCoin.$changeCoin;        $url="http://download.finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s={$str}=x";        $file = fopen($url,'r');        $arr=array();        while ($data = fgetcsv($file))        {            $arr[] = $data;        }        fclose($file);        if($arr){            //输出汇率            $result = json_encode(array("status"=>"ok","ret"=>$arr[0][1]));            exit($result);        }else{            exit($result);        }    }    exit($result);?>

PHP如何获取货币汇率?

4、点击进行测试,效果如下:

PHP如何获取货币汇率?

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢