在不使用PHP添加换行符的情况下附加到文件

时间:2017-04-10 17:24:29

标签: php fwrite file-put-contents

我想从 apriori_main 表中获取一些整数,并将它们作为逗号分隔值存储到文本文件中。对于每次迭代,我使用file_put_contents在下一行写入数据。使用fwrite会得到相同的结果。

我想在文本文件中输出:

1,2,3,4

但我得到的输出是:

1  
,2  
,3  
,4  

以下是代码段:

$y="";
$stmt='SELECT category FROM apriori_main where id='.$id.''; 
$nRows = $conn->query('select count(category) from apriori_main where id='.$id.'')->fetchColumn(); 
echo $nRows;

$file = "/opt/lampp/htdocs/ghi.txt";
$f = fopen($file, 'a+'); // Open in write mode
$count=1;

foreach($conn->query($stmt) as $row)
{ 
    if($count!=$nRows) 
    {
        $user = $row['category']."\n"; 
        $y=$user; $y=$y.",";
        $str=$y; echo $y;
        $count=$count+1;
    }
    else
    { 
        $user = $row['category']."\n";
        $y=$user; $str=$y; echo $y; 
    }
    file_put_contents($file, $str, FILE_APPEND);
}
fclose($f);

2 个答案:

答案 0 :(得分:0)

这就是所需要的:

$stmt = 'SELECT category FROM apriori_main where id='.$id.''; 
$file = "/opt/lampp/htdocs/ghi.txt";

foreach($conn->query($stmt) as $row)
{ 
    $str[] = $row['category'];
}
file_put_contents($file, implode(',', $str));
// only use FILE_APPEND if needed for the next time to append
  • 循环查询结果行
  • category附加到数组
  • 使用逗号,内嵌数组元素并写入文件

简而言之,你:

  1. 不需要查询计数
  2. 不需要打开文件
  3. 请勿使用\n这是换行符
  4. 不需要在循环中添加逗号,
  5. 不要编写每个循环迭代

答案 1 :(得分:-1)

我不知道你对这些值做了什么,但你似乎有很多不必要的变量声明。

我认为你可以有效地打破所有这一切

 $file = "/opt/lampp/htdocs/ghi.txt";
      $f = fopen($file, 'a+'); // Open in write mode
        $count=1;


      foreach($conn->query($stmt) as $row)
      { 
         if($count!=$nRows) 
         {
            $user = $row['category']."\n"; 
            $y=$user; $y=$y.",";
            $str=$y; echo $y;
            $count=$count+1;
         }
         else
         { 
            $user = $row['category']."\n";
            $y=$user; $str=$y; echo $y; 
         }
         file_put_contents($file, $str, FILE_APPEND);
     }
         fclose($f);

向下到此(最后只有一个文件操作)

$file = "/opt/lampp/htdocs/ghi.txt";

foreach($conn->query($stmt) as $row)
{ 
    $y[] = $row['category']; 
}
//output to screen
echo implode("<br>", $y);
//output to file
file_put_contents($file,implode(",", $y));
相关问题