我在这里使用了一些代码,将mysql查询数据转换为json数据并写入到一个文件中。问题出在哪里?为什么文件是零kb?
while($row = mysql_fetch_array($Query)){
$arr = array ('name'=>$row['name']);
$jsondata = json_encode($arr);
$countfile="data.txt";
if(!file_exists($countfile))
{
fopen($countfile,"w");
}
$fp = fopen($countfile, 'r');
fwrite($fp, $jsondata);
fclose($fp);
}发布于 2011-06-11 06:08:55
因为您正在以只读方式重新打开该文件
$fp = fopen($countfile, 'r');
试一试
$fp = fopen($countfile, 'w'); // to write
或
$fp = fopen($countfile, 'a'); // to append
您还可以在开始时打开要写入的文件,将行追加到变量中,然后将所有行一起写入文件。
$countfile="data.txt";
$fp = fopen($countfile, 'w');
while($row = mysql_fetch_array($Query))
{
$arr = array ('name'=>$row['name']);
$jsondata .= json_encode($arr) . "\n";
}
fwrite($fp, $jsondata);
fclose($fp);发布于 2011-06-11 06:09:18
有几件事。
你不需要(也应该避免)在每次迭代中打开文件只读(r)你打开文件
像这样的东西应该就行了
$countfile="data.txt";
$fp = fopen($countfile, 'w');
while($row = mysql_fetch_array($Query))
{
$arr = array ('name'=>$row['name']);
$jsondata = json_encode($arr);
fwrite($fp, $jsondata);
}
fclose($fp);此外,您可以将单独的json结构附加到文件中,这可能不是您想要的。您应该首先将想要存储的所有内容收集到一个json结构中,然后保存它。
$data = array();
while($row = mysql_fetch_array($Query))
{
$data[] = array ('name'=>$row['name']);
}
file_put_contents('data.txt', json_encode($data));这感觉更像你可能正在寻找的东西。
发布于 2011-06-11 06:08:15
您正在以只读方式打开文件
$fp = fopen($countfile, 'r');你也不需要
if(!file_exists($countfile))
{
fopen($countfile,"w");
} 只需使用:
$fp = fopen($countfile, 'w');https://stackoverflow.com/questions/6312535
复制相似问题