dongyuan6949 2013-07-24 09:09
浏览 115
已采纳

PHP - 将变量输出写入文件

I'd like to write the content of the variable $rows into the file out.txt.

The variable $rows is placed within a while loop and can be constituted by several different rows retrieved from a database.

Unfortunately, the following code just writes one single line (the last one precisely) of the expected output.

$myFile = "/var/www/test/out.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$content = $rows['text'];
fwrite($fh, $content);
fclose($fh);

Here is the PHP code (which is working) that allows me to see the contents of the $rows variable in the browser.

<?
if(isset($_POST['type'], $_POST['topic'], $_POST['tense'], $_POST['polarity']))
{
     $tipo = $_POST['type'];
     $argomento = $_POST['topic'];
     $tempo = $_POST['tense'];
     $segno = $_POST['polarity'];
   foreach ($tipo as $key_tipo => $value_tipo)
   {
         foreach ($argomento as $key_argomento => $value_argomento)
         {
                 foreach ($tempo as $key_tempo => $value_tempo)
                 {
                         foreach ($segno as $key_segno => $value_segno)
                         {
       $q_tip_arg_tem_seg = "SELECT * FROM entries WHERE type = '".$value_tipo."' AND topic = '".$value_argomento."' AND tense = '".$value_tempo."' AND polarity = '".$value_segno."'";  
       $qu_tip_arg_tem_seg = mysql_query($q_tip_arg_tem_seg);
       while ($rows = mysql_fetch_array($qu_tip_arg_tem_seg))
        {
            echo $rows['type']."<br />";
        }
   }
   }
   }
   }
}
else
{
   echo "You forgot to check something."."<br>"."Please select at least one type, topic, tense and polarity value."."<br>";
}
?>

Can you help me out? Thanks.

  • 写回答

3条回答 默认 最新

  • dongsuo0517 2013-07-24 09:12
    关注

    You only write out one line to the file. You probably want something like this:

    $myFile = "/var/www/test/out.txt";
    $fh = fopen($myFile, 'w') or die("can't open file");
    if ($fh) {
        while ($row = getrow()) {
            $content = $rows['text'];
            fwrite($fh, $content); // perhaps add a newline?
        }
        fclose($fh);
    }
    

    So, open the file, write all your stuff in it, then close it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 CSS实现渐隐虚线框
  • ¥15 有没有帮写代码做实验仿真的
  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?