jquery - Return the next line of a csv file each time a php script is called -
i using highcharts create "live" chart dynamically updating data. calls php file supposed parse csv , output result json.
my highcharts/jquery code this:
function requestdata() { $.ajax({ url: 'datatest.php', success: function(point) { var series = chart.series[0], shift = series.data.length > 20; // shift if series longer 20 // add point chart.series[0].addpoint(eval(point), true, shift); // call again after 1 second settimeout(requestdata, 10000); }, cache: false }); }
my datatest.php file thus:
<?php header("content-type: text/json"); $handle = fopen("windspeed.csv", "r"); $windvals = fgetcsv($handle, 1000, ","); $x = time() * 1000; $y = $windvals[0]; // create php array , echo json $ret = array($x, $y); echo json_encode($ret); ?>
however, can't figure out how pass next line of csv each time php script called; passes same json values (in first line of csv) highcharts shows flat straight line.
i'm extremely new this, there way parse next line of csv file every time php script called? or there better alternative way of doing this?
thanks,
regards, kev
i'm not great javascript , don't remember scoping rules posted, here php. should work storing line in session , increment each time script called. uses file()
read lines array:
session_start(); $_session['line'] = isset($_session['line']) ? ++$_session['line'] : 0; $lines = file('windspeed.csv'); if(isset($lines[$_session['line']])) { $windvals = str_getcsv($lines[$_session['line']], ','); } else { $_session['line'] = 0; } header("content-type: text/json"); $x = time() * 1000; $y = $windvals[0]; $ret = array($x, $y); echo json_encode($ret);
if file large might want loop through using fgetcsv()
until reach proper line. like:
session_start(); $_session['line'] = isset($_session['line']) ? ++$_session['line'] : 0; $handle = fopen('windspeed.csv', 'r'); $i = 0; while(($windvals = fgetcsv($handle, 1000, ',')) && $i <= $_session['line']) { $i++; } if(!$windvals) { $_session['line'] = 0; } header("content-type: text/json"); $x = time() * 1000; $y = $windvals[0]; $ret = array($x, $y); echo json_encode($ret);
Comments
Post a Comment