2010-03-18 48 views
89
CREATE TABLE Posts 
{ 
id INT PRIMARY KEY AUTO_INCREMENT, 
title VARCHAR(200), 
url VARCHAR(200) 
} 

json.php代碼如何用PHP生成.json文件?

<?php 
$sql=mysql_query("select * from Posts limit 20"); 
echo '{"posts": ['; 
while($row=mysql_fetch_array($sql)) 
{ 
$title=$row['title']; 
$url=$row['url']; 
echo ' 

{ 

"title":"'.$title.'", 

"url":"'.$url.'" 

},'; 
} 
echo ']}'; 

?> 

我不得不產生results.json文件。

回答

177

這裏是一個示例代碼:

<?php 
$sql="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); 


?> 
+1

我在我的項目中使用了這段代碼。 results.json文件在本地主機上運行良好,並在遠程服務器上失敗。你能解釋爲什麼那麼.. – 2012-12-21 05:53:34

+3

在您的服務器設置中,可以關閉Fwrite – Chris 2013-01-19 20:28:34

+0

allthough雖然這很好,也許是因爲我現在使用PHP 5,並且在發佈此答案時它不可用,但是您可以擺脫$ result =行和內部你的while循環只是讓mysql_feth_array($ sql) – 2014-02-07 13:20:34

24

將您提取的值插入數組而不是回顯。

如果您的數據爲$rows,則使用file_put_contents()並將json_encode($rows)插入該文件中。

+0

我看到您的答案已發佈在最上面的答案之前。如果只有你已經放了一些示例代碼,你會得到更多的選票。 – 2015-12-31 14:29:16

3

如果你拉動態記錄最好是有一個創建一個JSON表示和每次不創建一個文件1個PHP文件。

my_json.php

$array = array(
    'title' => $title, 
    'url' => $url 
); 

echo stripslashes(json_encode($array)); 

然後在你的腳本中的路徑設置爲文件my_json.php

+1

當我嘗試運行getJason時,我得到*資源解釋爲腳本,但與MIME類型文本/ html *在控制檯中。 – noobcode 2012-12-06 10:22:03

+0

@noobcode爲了解決這個問題,我想你應該在'my_json.php'中設置'Content-Type'標題。 – 2015-01-24 15:38:42

17

使用此:

$json_data = json_encode($posts); 
file_put_contents('myfile.json', $json_data); 

爲我工作。

3

這裏,我已經提到的簡單了Syntex用於創建JSON文件並打印JSON文件在相當的方式內的數組值。

$array = array('name' => $name,'id' => $id,'url' => $url); 
$fp = fopen('results.json', 'w'); 
fwrite($fp, json_encode($array, JSON_PRETTY_PRINT)); //here it will print the array pretty 
fclose($fp); 

希望它會爲你的作品....

0

首先,你需要將其解碼:

$jsonString = file_get_contents('jsonFile.json'); 
$data = json_decode($jsonString, true); 

然後更改數據:

$data[0]['activity_name'] = "TENNIS"; 
// or if you want to change all entries with activity_code "1" 
foreach ($data as $key => $entry) { 
    if ($entry['activity_code'] == '1') { 
     $data[$key]['activity_name'] = "TENNIS"; 
    } 
} 

然後再 - 編碼並將其保存迴文件中:

$newJsonString = json_encode($data); 
file_put_contents('jsonFile.json', $newJsonString); 

copy