Using PHP to append JSON file with new MySQL data -
i'm working on reading information in database json file. code have reads file fine i'm looking way append new data not present in file already. every time run code adds of information stored in database each time.
$con = mysql_connect('localhost', '', '') or die('error connecting server'); mysql_select_db('twitter', $con); $file = 'file.json'; $query = mysql_query('select * sample_data'); //define columns $table = array(); $table['cols'] = array( array('label' => 'username', 'type' => 'string'), array('label' => 'retweet_count', 'type' => 'number'), array('label' => 'origin', 'type' => 'string'), array('label' => 'destination', 'type' => 'string'), array('label' => 'text', 'type' => 'string'), array('label' => 'sentiment_type', 'type' => 'string'), array('label' => 'sentiment_score', 'type' => 'number'), array('label' => 'profile_picture', 'type' => 'string'), array('label' => 'tweetid', 'type' => 'number') ); $rows = array(); while($r = mysql_fetch_assoc($query)) { $temp = array(); // each column needs have data inserted via $temp array $temp[] = array('v' => $r['username']); $temp[] = array('v' => (int) $r['retweet_count']); // typecast numbers appropriate type (int or float) needed - otherwise input strings $temp[] = array('v' => $r['origin']); $temp[] = array('v' => $r['destination']); $temp[] = array('v' => $r['text']); $temp[] = array('v' => $r['sentiment_type']); $temp[] = array('v' => (double) $r['sentiment_score']); $temp[] = array('v' => $r['profile_picture']); $temp[] = array('v' => (int) $r['tweetid']); // insert temp array $rows $rows[] = array('c' => $temp); } // populate table rows of data $table['rows'] = $rows; file_put_contents($file, json_encode($table, json_force_object), file_append | lock_ex); // read out echo file_get_contents($file); // set header; first 2 prevent ie caching queries header('cache-control: no-cache, must-revalidate'); header('expires: mon, 26 jul 1997 05:00:00 gmt'); header('content-type: application/json');
thank help!
you can't "append" new data json string, destroys json introducing syntax errors. remember json string has syntactically valid javascript.
so if json string starts out as
['a','b','c'];
and tack on couple new array elements, you'll end with
['a','b','c']['d',e'];
and garbage because that's not valid json/javascript.
you need decode json native php structure, appending there, re-encode json:
$json = '....'; $array = json_decode($json); while( ... ) { $array[] = $new_data; } $json = json_encode($array);
Comments
Post a Comment