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

时间:2016-06-02 08:22:28

标签: php arrays json ajax yahoo-finance

我想知道如何动态更新货币汇率变量php/AJAX/json $CurrencyValue(来自雅虎财务的货币价值)只有在变量与以前不同时才会更新。 / p>

例如:

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).

重要的是页面不会刷新,只有变量$CurrencyValue如果变量发生变化我想得到确切的日期。

    <?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; ?>

谢谢

修改

我有一个通过YAHOO FINANCE与PHP / AJAX一起进行欧元兑换的代码。我的问题是如何将发布的数据图表与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,
                    }]
  

{&#34; rate&#34;:&#34; 1.1200&#34;,&#34; time&#34;:&#34; 2016-06-02 12:41:06&#34;}   {&#34; rate&#34;:&#34; 1.1205&#34;,&#34; time&#34;:&#34; 2016-06-02 12:41:08&#34;}   {&#34; rate&#34;:&#34; 1.1199&#34;,&#34; time&#34;:&#34; 2016-06-02 12:41:10&#34;}   {&#34; rate&#34;:&#34; 1.1199&#34;,&#34; time&#34;:&#34; 2016-06-02 12:41:12&#34;}

守则:

    <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>

谢谢。

1 个答案:

答案 0 :(得分:1)

<?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();
}