2016-12-08 20 views
0

我有一个data.txt文件,它将文本内容从textarea发布到带有PHP的HTML页面。PHP在Textarea中转换新行至<BR>

我希望文本区域可以将新行作为<br>元素来读取,因此在创建新行时它们全都不在同一行上。

例子:

Hello 
Hello 

等于

HelloHello 

但我想它等于

Hello 
Hello 

我已经尝试实现n2lbr但很难与我的系统来实现这样如果你打算建议请说明如何。

所以这里是我的代码:

HTML:

<form method="POST" action="process.php" onsubmit='return validate()' > 
    <textarea cols='60' rows='8' id="input1" type="text" name="myInputName" style="background:white;border:2px solid #dfdfdf;color:black;height:50px;"></textarea> 

    <input type="submit" name="submitButton" value="Post" style="width:60px;height:55px;background:white;color:black;border:2px solid #dfdfdf;" class="cbutton" /> 
    </form> 

    <form method="POST" action="clear.php"> 
    <input type="submit" name="Clear" value="Erase" style="width:265px;height:30px;background:white;color:black;border:2px solid #dfdfdf;margin-top:2px;" class="cbutton"/> 
    </form> 
</div> 
<p style="font-size:35px;text-align:center;font-family:Raleway;">To do List</p> 
<div id="list2" style=""> 

<?php 
    $myfilename = "data.txt"; 
    if (file_exists($myfilename)) { 
    echo file_get_contents($myfilename); 
    nl2br($myfilename); 
    } 
?> 

PHP(PROCESS.PHP):

<?php 
    // We will put the data into a file in the current directory called "data.txt" 
    // But first of all, we need to check if the user actually pushed submit 

    if (isset($_POST['submitButton'])) { 

    // The user clicked submit 
    // Put the contents of the text into the file 
    file_put_contents('./data.txt', $_POST['myInputName'] . '</br>', FILE_APPEND); 
    $str = $_POST["myInputName"] echo nl2br($str); 

    // ./data.txt: the text file in which the data will be stored 
    // $_POST['myInputName']: What the user put in the form field named "myInputName" 
    // FILE_APPEND: This tells the function to append to the file and not to overwrite it. 
    header('Location: index.php'); 
    } 

提前感谢!

已经有了一个这样的麻烦。

+0

在您的html中,您在textarea之外回显文件内容 - 因此永远不会工作。你也可以将nl2br应用于文件名,而不是内容。 –

+1

你不能只是'echo nl2br(file_get_contents($ myfilename))'? – junkfoodjunkie

+0

我现在就试试。我已经尝试过所有我能想到的东西,所以它在textarea之外可能只是试验我能想到的所有其他东西。 –

回答

0

你没有回应nl2br()的结果,你只是回应文件的原始内容,然后调用nl2br()并忽略它返回的内容。它应该是:

echo nl2br(file_get_contents($myfilename)); 
0

只需使用PHP的内置功能:nl2br()和应该做它像这样:使用file_get_contents()像这样过筛

<?php 
     $stringFromTextArea = "The Quick brown Fox\nStumble upon\nA Bag of Worms\n"; 
     $stringWithBR  = nl2br($stringFromTextArea); 
     echo $stringWithBR; 

同样的功能仍然可以用于内容:

<?php 
     $stringFromFile  = file_get_contents($pathToFile); 
     $stringWithBR  = nl2br($stringFromFile); 
     echo $stringWithBR;