dongyu1918 2016-06-02 08:22
浏览 59
已采纳

如何使用php / json / ajax动态更新货币汇率变量

I would like to know how to update variable dynamically of currency rate WITH php/AJAX/json that $CurrencyValue (the currency value from yahoo finance) will update only if the variable is different than it was before.

For example:

on 01/01/2016 10:00 USDINR gate was 67.454.
1/01/2016 10:01 USDINR gate was 67.104 (the variable $CurrencyValue be updated).
1/01/2016 10:02 gate of USDINR remains 67.104 (the variable $CurrencyValue not be updated).
1/01/2016 10:03 USDINR gate was 67.024 (so the variable $CurrencyValue be updated).

It is important the page will not refreshed, only the variable $CurrencyValue also if the variable changed I would like to get The exact date.

    <?php
    $from   = 'USD'; $to     = 'INR'; $url = 'http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s='. $from . $to .'=X'; $currencyValue = 0;  $handle = fopen($url, 'r');  if ($handle) { 
        while (($data = fgetcsv($handle, 1024, ',', '"')) !== FALSE) 
        { 
            $currencyValue = $data[1];
        }
        fclose($handle);

    }   $date = date('l jS \of F Y h:i:s A');

    ?>


Value of 1 USDINR is  <?php echo $currencyValue. ' - ' .$date; ?>

Thank you

EDIT

I have a code of euro-dollar exchange via YAHOO FINANCE works with PHP / AJAX. My question is how to integrate the data released chart works with CHARTS.JS

labels: ["2016-06-02 12:41:06", "2016-06-02 12:41:08"],
               datasets: [{
label: "My Third dataset - No bezier",
       data: [1.1200,1.1205],
              lineTension: 0,
                   fill: false,
                    }]

{"rate":"1.1200","time":"2016-06-02 12:41:06"} {"rate":"1.1205","time":"2016-06-02 12:41:08"} {"rate":"1.1199","time":"2016-06-02 12:41:10"} {"rate":"1.1199","time":"2016-06-02 12:41:12"}

The Code:

    <script src="Chart.bundle.min.js"></script>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <style>
        canvas {
            -moz-user-select: none;
            -webkit-user-select: none;
            -ms-user-select: none;
        }
    </style>

    <?php
if(isset($_GET['fetchOnly'])){
    $from   = 'eur';
    $to     = 'usd';
    $url = 'http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s='. $from . $to .'=X'; 
    $response = array();
    $handle = fopen($url, 'r'); 
    if ($handle) { 
        while (($data = fgetcsv($handle, 1024, ',', '"')) !== FALSE) 
        { 
            $response['rate'] = $data[1]; 
            $response['time'] = date("Y-m-d H:i:s");
        }
        fclose($handle);

    }  
    echo json_encode($response);
    die();
} 
?>
<div id="responseText"></div>
<script>
// run the function, it will re-run itself
fetchRate();

function fetchRate() {
    // create the new AJAX Object
    xmlhttp = new XMLHttpRequest();
    // this handles the request
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
            // if the request came back successfully
            if(xmlhttp.status == 200){
                // write the response to a div
                div = document.getElementById("responseText")
                div.innerHTML = div.innerHTML + '<br />'+ xmlhttp.responseText;
            }else{
            // if the request had an error
                div.innerHTML = div.innerHTML + '<br />Error fetching rates error code : '+xmlhttp.status;
            }
            // rerun this function to fetch updates
            setTimeout(fetchRate,1000);
        }
    };
    // open the AJAX Object
    xmlhttp.open("GET", "<?= basename(__FILE__) ?>?fetchOnly", true);
    // send the AJAX request
    xmlhttp.send();
}
</script>
    <div style="width:100%;">
        <canvas id="canvas"></canvas>
    </div>

    <script>
        var MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
        var randomScalingFactor = function() {
            return Math.round(Math.random() * 100 * (Math.random() > 0.5 ? -1 : 1));
        };
        var randomColorFactor = function() {
            return Math.round(Math.random() * 255);
        };
        var randomColor = function(opacity) {
            return 'rgba(' + randomColorFactor() + ',' + randomColorFactor() + ',' + randomColorFactor() + ',' + (opacity || '.3') + ')';
        };

        var config = {
            type: 'line',
            data: {
                labels: ["2016-06-02 12:36:05", "2016-06-02 12:37:05"],
                datasets: [{
                    label: "My Third dataset - No bezier",
                    data: [1,2],
                    lineTension: 0,
                    fill: false,
                }]
            },
            options: {
                responsive: true,
                legend: {
                    position: 'bottom',
                },
                hover: {
                    mode: 'label'
                },
                scales: {
                    xAxes: [{
                        display: true,
                        scaleLabel: {
                            display: true,
                            labelString: 'Month'
                        }
                    }],
                    yAxes: [{
                        display: true,
                        scaleLabel: {
                            display: true,
                            labelString: 'Value'
                        }
                    }]
                },
                title: {
                    display: true,
                    text: 'Chart.js Line Chart - Legend'
                }
            }
        };

        $.each(config.data.datasets, function(i, dataset) {
            var background = randomColor(0.5);
            dataset.borderColor = background;
            dataset.backgroundColor = background;
            dataset.pointBorderColor = background;
            dataset.pointBackgroundColor = background;
            dataset.pointBorderWidth = 1;
        });

        window.onload = function() {
            var ctx = document.getElementById("canvas").getContext("2d");
            window.myLine = new Chart(ctx, config);
        };

        $('#randomizeData').click(function() {
            $.each(config.data.datasets, function(i, dataset) {
                dataset.data = dataset.data.map(function() {
                    return randomScalingFactor();
                });

            });

            window.myLine.update();
        });

        $('#addDataset').click(function() {
            var background = randomColor(0.5);
            var newDataset = {
                label: 'Dataset ' + config.data.datasets.length,
                borderColor: background,
                backgroundColor: background,
                pointBorderColor: background,
                pointBackgroundColor: background,
                pointBorderWidth: 1,
                fill: false,
                data: [],
            };

            for (var index = 0; index < config.data.labels.length; ++index) {
                newDataset.data.push(randomScalingFactor());
            }

            config.data.datasets.push(newDataset);
            window.myLine.update();
        });

        $('#addData').click(function() {
            if (config.data.datasets.length > 0) {
                var month = MONTHS[config.data.labels.length % MONTHS.length];
                config.data.labels.push(month);

                $.each(config.data.datasets, function(i, dataset) {
                    dataset.data.push(randomScalingFactor());
                });

                window.myLine.update();
            }
        });

        $('#removeDataset').click(function() {
            config.data.datasets.splice(0, 1);
            window.myLine.update();
        });

        $('#removeData').click(function() {
            config.data.labels.splice(-1, 1); // remove the label first

            config.data.datasets.forEach(function(dataset, datasetIndex) {
                dataset.data.pop();
            });

            window.myLine.update();
        });
    </script>

Thank you.

  • 写回答

1条回答 默认 最新

  • douzi7711 2016-06-02 08:35
    关注
    <?php
    if(isset($_GET['fetchOnly'])){
        $from   = 'USD';
        $to     = 'INR';
        $url = 'http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s='. $from . $to .'=X'; 
        $response = array();
        $handle = fopen($url, 'r'); 
        if ($handle) { 
            while (($data = fgetcsv($handle, 1024, ',', '"')) !== FALSE) 
            { 
                $response['rate'] = $data[1]; 
                $response['date'] = $data[2];
                $response['time'] = $data[3];
            }
            fclose($handle);
            fclose($handle);
        }  
        echo json_encode($response);
        die();
    } 
    ?>
    <div id="responseText"></div>
    <script>
    // run the function, it will re-run itself
    fetchRate();
    
    function fetchRate() {
        // create the new AJAX Object
        xmlhttp = new XMLHttpRequest();
        // this handles the request
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
                // if the request came back successfully
                if(xmlhttp.status == 200){
                    // write the response to a div
                    div = document.getElementById("responseText")
                    div.innerHTML = div.innerHTML + '<br />'+ xmlhttp.responseText;
                }else{
                // if the request had an error
                    div.innerHTML = div.innerHTML + '<br />Error fetching rates error code : '+xmlhttp.status;
                }
                // rerun this function to fetch updates
                setTimeout(fetchRate,3000);
            }
        };
        // open the AJAX Object
        xmlhttp.open("GET", "<?= basename(__FILE__) ?>?fetchOnly", true);
        // send the AJAX request
        xmlhttp.send();
    }
    

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 请求分析基于spring boot+vue的前后端分离的项目
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥200 关于#c++#的问题,请各位专家解答!网站的邀请码
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?