2013-07-17 34 views
1

我正在讀取數據庫中的信息到JSON文件。我已經讀取了該文件的代碼,但是我正在尋找的是僅添加文件中不存在的新數據的方法。每次運行我的代碼時,它都會每次添加存儲在數據庫中的所有信息。使用PHP附加JSON文件與新的MySQL數據

$con = mysql_connect('localhost', '', '') or die('Error connecting to server'); 

mysql_select_db('twitter', $con); 

$file = 'file.json'; 

$query = mysql_query('SELECT * FROM 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 to have data inserted via the $temp array 
    $temp[] = array('v' => $r['Username']); 
    $temp[] = array('v' => (int) $r['Retweet_count']); // typecast all numbers to the appropriate type (int or float) as needed - otherwise they are input as 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 the temp array into $rows 
    $rows[] = array('c' => $temp); 
} 

// populate the table with rows of data 
$table['rows'] = $rows; 

file_put_contents($file, json_encode($table, JSON_FORCE_OBJECT), FILE_APPEND | LOCK_EX); 

// Read it back out with 
echo file_get_contents($file); 


// set up header; first two prevent IE from caching queries 
header('Cache-Control: no-cache, must-revalidate'); 
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); 
header('Content-type: application/json'); 

謝謝你的幫忙!

+1

你可以添加一個列到數據庫將其標記爲true,如果數據已被導出,然後將選擇更改爲僅獲取虛假項目? – ObieMD5

+0

@ ObieMD5建議是一個很好的。但是,爲什麼需要附加?你能不能每次擦掉數據? –

+0

您也可以'json_decode'文件,確定哪個是最後一個記錄,然後調整您的查詢以檢索最後一個元素之後的條目。 –

回答

0

你不能只是「追加」新的數據到json字符串,這通常會通過引入語法錯誤來破壞json。請記住,json字符串必須是語法上有效的javascript。

所以,如果你的JSON字符串開始作爲

['a','b','c']; 

,你釘在了幾個新的數組元素,你會擁有

['a','b','c']['d',e']; 

,並得到垃圾,因爲這不是有效的JSON/JavaScript的。

您需要DECODE的JSON回原生PHP結構,做你的追加那裏,然後重新編碼成JSON:

$json = '....'; 
$array = json_decode($json); 

while(...) { 
    $array[] = $new_data; 
} 
$json = json_encode($array);