2014-02-16 54 views
0

我有一個php腳本,它將一個名爲results.json的文件添加到我的在線服務器中,無論php腳本在哪裏;用PHP編輯.json

<?php 
    $sql=mysql_query("select * from Posts limit 20"); 

    $response = array(); 
    $posts = array(); 
    $result=mysql_query($sql); 

    while($row=mysql_fetch_array($result)) 
    { 
     $title=$row['title']; 
     $url=$row['url']; 

     $posts[] = array('title'=> $title, 'url'=> $url); 

    } 

    $response['posts'] = $posts; 

    $fp = fopen('results.json', 'w'); 
    fwrite($fp, json_encode($response)); 
    fclose($fp); 


?> 

我想要做的是;編輯results.json文件,或添加到它的包含,而不是每次創建一個新的。你有什麼建議?

+4

爲什麼要這麼做?最安全的方法是將整個東西加載到PHP對象中,修改數據並再次輸出。但是如果你的文件很大,這可能會很慢。 – Brad

+2

1)從文件中加載json文本2)解碼json文本 - > php結構3)修改php結構4)將結構編碼爲json並寫入文件。你可以**不**直接修改原始的JSON文本。代碼中最微小的錯誤會引入語法錯誤並殺死整個結構。 –

+0

你能給我一個代碼示例;採取並添加到JSON文件? – raklar

回答

2

你可以做這樣的事情之前添加行;

$json_data = json_decode(file_get_contents('results.json')); 
array_push($json_data, 'some value'); 
file_put_contents('results.json', json_encode($json_data)); 
2

這個最簡單的解決辦法是JSON文件解碼成一個對象,然後重寫

$response = json_decode(file_get_contents("results.json")); 
$response['posts'][] = array(...); 
$fp = fopen('results.json', 'w'); 
fwrite($fp, json_encode($response)); 
fclose($fp);