2011-05-26 146 views
1

我正在尝试将所有对所写入表单的响应总计保留下来,但我无法将其设置为每个响应需要换行。我的代码如下。我只是想让它更容易阅读,因为现在发生的情况是,所有的反应都卡在了一起,希望每一个反应都在一条新线上。我尝试了一些东西,让他们在代码中注释,结果如何。提前致谢。PHP,写入文件时的换行符

<?php 
if (isset($_POST['sometext'])) 
    { 
    $myFile = "testFile.txt"; 
    $thetext=$_POST['sometext'] ;//added + "\n" here but all response turned to 0 
    writemyfile($myFile,$thetext,"a"); 
    } else 
    { 
    $thetext="Enter text here"; 
    } 

function readmyfile($thefile) 
    { 
     $file = fopen($thefile, "r") or exit("Unable to open file!"); 
     //Output a line of the file until the end is reached 
     while(!feof($file)) 
     { 
      echo fgets($file). "<br />"; 
     } 
     fclose($file); 
    } 

function writemyfile($thefilename,$data,$mode) 
    { 
     $myfile=fopen($thefilename,$mode); 
     fwrite($myfile, $data); // added + "\n" here and responses turned 0 
     fclose($myfile); 
    } 
?> 
<html> 
    <head> 
     <title> Zain's Test Site</title></head> 
    <body> 
     <form method="post" action="<?php echo $php_self ?>"> 
      <input type="text" name="sometext" value="<?php echo $thetext ?>" > 
      <input type="submit" name="Submit" value="Click this button"> 
     </form> 
     <?php readmyfile("testFile.txt"); ?> 
    </body> 

+1

PHP有一个常量,'PHP_EOL',它包含你的主机平台的行尾字符。使用它比'\ n'更安全,除非您专门为其他平台读取/写入文件。 – 2011-05-26 15:28:23

+0

谢谢你告诉我,我会做一些研究 – Zaask 2011-05-26 15:36:37

回答

1

你可以尝试追加换行符(\ n)输出到$ thetext变量是这样的:

$thetext=$_POST['sometext'] . "\n"; 

记住使用 ''作为连接运算符,并在换行符周围使用双引号。

+0

谢谢。 Idk为什么我没有意识到运营商。对不起,浪费你的时间。 – Zaask 2011-05-26 15:34:17

+0

这完全不是浪费。这就是为什么在这里。 :) – 2011-05-26 15:44:49

1
$thetext."\n" 

在PHP您连接使用字符串 “”,你在javascript “+” 使用。

+0

谢谢。 Idk为什么我没有意识到运营商。对不起,浪费你的时间。 – Zaask 2011-05-26 15:33:47

1

$text = $text."\n" “\ n” 呢?这里

错误的一些文字填写答案

+0

谢谢。 Idk为什么我没有意识到运营商。对不起,浪费你的时间。 – Zaask 2011-05-26 15:33:52

1
fwrite($myfile, $data); // added + "\n" here and responses turned 0 

的Concat的字符串操作是()否(+)

您还可以简化您的脚本正是如此

echo nl2br(get_file_contents($file)); 
+0

谢谢。 Idk为什么我没有意识到运营商。对不起,浪费你的时间。 – Zaask 2011-05-26 15:33:41