MySQL的foreach fwrite [英] mysql foreach fwrite

查看:157
本文介绍了MySQL的foreach fwrite的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里使用了一些代码,将mysql的查询数据转换成json数据并写入文件。哪里有问题?为什么文件是零kb?

  while($ row = mysql_fetch_array($ Query)){
$ arr = array('name'=> ; $行[ '名称']);
$ jsondata = json_encode($ arr);
$ countfile =data.txt;
if(!file_exists($ countfile))
{
fopen($ countfile,w);
}
$ fp = fopen($ countfile,'r');
fwrite($ fp,$ jsondata);
fclose($ fp);

$ / code $


解决方案

因为你重新开放文件为只读
$ b $ $ fp = fopen($ countfile,'r');



try

$ fp = fopen($ countfile,'w'); //写入





$ fp = fopen($ countfile,'a'); //添加



您也可以在开始时打开文件进行写入,将行添加到变量中,然后将它们一起写入

  $ 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);


I use some code here, transfer mysql query data into json data and write into a file. where is the problem? why the file is zero 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);
}

解决方案

Because you're reopening the file as read only

$fp = fopen($countfile, 'r');

try

$fp = fopen($countfile, 'w'); // to write

or

$fp = fopen($countfile, 'a'); // to append

you could also open the file for writing at the start, append your rows in a variable and then write it all together to the file.

$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);

这篇关于MySQL的foreach fwrite的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆