【问题标题】:PHP Line break in array数组中的PHP换行符
【发布时间】:2018-03-17 20:21:57
【问题描述】:

我尝试在 php 中连接三个 HTML 表单字段值(名称、说词、邮件)并写入我服务器上的单个 txt 文件:

每个值都应该在 txt 字段中的一个新行上,这就是我在数组中添加“\n”的原因......我的错误在哪里?

非常感谢您的帮助!

$name = $_POST['name'];
$saywords = $_POST['saywords'];
$mail = $_POST['mail'];

$data = array($name,  . "\n" $mail, . "\n" $saywords);

file_put_contents("$t.$ip.txt",$data); // Will put the text to file

【问题讨论】:

  • file_put_contents($file, implode('\n', $data)) 并从数组中删除新行
  • 你为什么要创建一个数组?就做$data = $name . "\n" . $mail . "\n" . $saywords;
  • 完美!非常感谢!! :)

标签: php arrays forms line-breaks


【解决方案1】:

你有两个问题:

  • $data 应该是字符串而不是数组
  • . 连接左侧和右侧:"abc" . "def" 变为 "abcdef"
    • . "\n" 甚至. "\n" $mail 中将点放在首位在 PHP 中是没有意义的,因此会出现解析错误。

$data = $name . "\n" . $mail . "\n" . $saywords; 替换您的$data = 行,您就可以开始了。

【讨论】:

  • 完美!非常感谢!!
【解决方案2】:

我没有看到 array 的用法,你可以像这样连接它们:

$data = $name . "\n" . $mail . "\n" . $saywords ;

【讨论】:

  • 完美!非常感谢!!
【解决方案3】:

这取决于服务器的操作系统。 试试"\r\n" 而不是"\n"

【讨论】:

  • 如果你看 OP 的代码,有一些更大的问题。
【解决方案4】:

好的,这是我的镜头。

/*first of all, you should always check if posted vars are actually set
and not empty. for that, you can use an universal function "empty", which
checks if the variable is set / not null / not an empty string / not 0. 
In such way you will avoid PHP warnings, when some of these variables 
will not be set*/

        $name = !empty($_POST['name']) ? $_POST['name'] : '';
        $saywords = !empty($_POST['saywords']) ? : $_POST['saywords'] : '';;
        $mail = !empty($_POST['mail']) ? $_POST['mail'] : '';

/*Secondly, do not use \n, \r, \r\n, because these are platform specific. 
Use PHP_EOL constant, it will do the job perfectly, by choosing 
what type of line-break to use best.

    As others mentioned - in your scenario, the string would be better solution. 
Add everything into string, and then put its contents into file. Avoid using 
double quotes, when you define PHP strings, and use single quotes instead - for 
performance and cleaner code.

    */


        $data = 'Name: '.$name.PHP_EOL.'E-Mail: '.$mail.PHP_EOL.'Message: '.$saywords.PHP_EOL.PHP_EOL;


        file_put_contents($t.$ip.'.txt', $data); // Will put the text to file

顺便说一句,我强烈建议在将数据保存到该 txt 文件之前还添加一些额外的验证。使用此代码,某人可以通过无限制地发布大量数据来轻松弄乱您的 txt 文件的内容。

提示:

1) 只接受长度和字符有限的名称(不允许使用特殊符号或换行符 - 您也可以在保存之前将它们过滤掉)

2) 验证已输入的电子邮件 - 如果格式正确,电子邮件地址的域是否存在 mx 记录,等等...

3) 接受长度有限的“saywords”,如果需要 - 拒绝或过滤掉特殊字符。

通过这种方式,您将获得更清晰的提交。

【讨论】:

    【解决方案5】:

    像使用 html 代码一样使用<br />

    【讨论】:

    • OP 将数据保存在文本文件中,而不是输出,所以\n 是正确的(不是我的反对票,顺便说一句)。
    猜你喜欢
    • 2021-07-03
    • 1970-01-01
    • 1970-01-01
    • 2012-10-30
    • 2015-06-03
    • 1970-01-01
    • 2019-03-21
    • 1970-01-01
    相关资源
    最近更新 更多