dongyu1918
2016-06-02 08:22
浏览 53

如何使用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();
    }
    

    打赏 评论

相关推荐 更多相似问题