将查询结果导出到json文件中

时间:2014-10-02 08:21:05

标签: javascript php json file export

我需要将从数据库中提取的数据通过php导出到json文件中,以便像这样在json文件中输出。我需要在每一行之间换行。

" ID":" ID&#34 ;, "名称":"名称",

这是我的查询已经有id和name。但我不知道如何将它们导出为文件。

while($row = mysql_fetch_array($result))
{
echo $row['id'];
echo $row['name'];
}

1 个答案:

答案 0 :(得分:2)

$data = [];    
while($row = mysql_fetch_array()) {
    $data[] = $row;
}

$txt = json_encode($data);

$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
fwrite($myfile, $txt);

fclose($myfile);

答案是这样的:

[
    { "id": "idvalue", "name": "namevalue" },
    ...
]
相关问题