使用 PHP 追加到文件而不添加换行符

Append to file without adding newlines using PHP

我想从 apriori_main table 中取出一些整数,并将它们作为逗号分隔值存储到文本文件中。对于每次迭代,我使用 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);

这就是所需要的:

$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. 不要写每个循环迭代

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

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

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