【问题标题】:PHP, Line break when writting to a filePHP,写入文件时换行
【发布时间】:2011-09-02 17:04:34
【问题描述】:

我正在尝试对我所写的表格的所有回复进行汇总,但我在制作时遇到了麻烦,以便每个回复都换行。我在下面有我的代码。我只是想让它更容易阅读,因为现在发生的事情是所有的响应都挤在一起,希望每个响应都在一个新的行上。我尝试了一些东西,并让它们在代码中注释以及结果是什么。提前致谢。

<?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>

【问题讨论】:

  • PHP 有一个常量 PHP_EOL,其中包含您的主机平台的行尾字符。使用它比使用 \n 更安全,除非您专门为另一个平台读取/写入文件。
  • 谢谢你告诉我这件事,我会做一些研究

标签: php file-io webforms file-writing


【解决方案1】:

您可以尝试将换行符 (\n) 附加到 $thetext 变量,如下所示:

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

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

【讨论】:

  • 谢谢。不知道为什么我没有意识到运营商。很抱歉浪费了您的时间。
  • 这根本不是浪费。这就是为什么在这里。 :)
【解决方案2】:
$thetext."\n"

在 php 中使用“.”连接字符串,在 javascript 中使用“+”。

【讨论】:

  • 谢谢。不知道为什么我没有意识到运营商。很抱歉浪费了您的时间。
【解决方案3】:

使用换行符“\n”而不是用于 html 的 br

【讨论】:

    【解决方案4】:

    $text = $text."\n" ?

    这里还有一些文字来填写答案

    【讨论】:

    • 谢谢。不知道为什么我没有意识到运营商。很抱歉浪费了您的时间。
    【解决方案5】:
     fwrite($myfile, $data); // added + "\n" here and responses turned 0
    

    连接字符串运算符是 (.) 而不是 (+)

    你也可以这样简化你的脚本

     echo nl2br(get_file_contents($file));
    

    【讨论】:

    • 谢谢。不知道为什么我没有意识到运营商。很抱歉浪费了您的时间。
    猜你喜欢
    • 1970-01-01
    • 2011-03-05
    • 2011-05-10
    • 2020-07-15
    • 1970-01-01
    • 1970-01-01
    • 2010-11-15
    相关资源
    最近更新 更多