【问题标题】:PHP fwrite function new linePHP fwrite 函数新行
【发布时间】:2017-07-18 03:32:04
【问题描述】:

我有这个代码:

//This line is for the input that i've looped above my code, it's a URL
$textAr[$i] = str_replace("\r\n","", $textAr[$i]);

//This is for implode purposes
$finalArray = array($textAr[$i], $m1, $m2, $m3, $m4, $m5, $m6);

//When i echo this variable, $test, the URL is in the line along with the implode arrays
$test = implode($finalArray, "***");
echo $test."\n";

//This is for writing into my text file
fwrite($sitesTxt, implode($finalArray, "***")."\n");

我遇到了一种错误,在我输入 3 个 URL 后,第一个和第二个 URL 在我写入文件后有新行,但我输入的最后一个 URL 与内爆数组一致.我什至修剪了 $textArr,但我不断收到新行。

预期输出:

https://docs.google.com***false***false***false***false***false***false***
https://stackoverflow.com***false***false***false***false***false***false***
https://stackexchange.com***false***false***false***false***false***false***

我在 txt 文件中得到的输出:

https://docs.google.com
***false***false***false***false***false***false***
https://stackoverflow.com
***false***false***false***false***false***false***
https://stackexchange.com***false***false***false***false***false***false***

【问题讨论】:

  • 请发布您的完整代码(包括循环、示例数据)
  • 你能告诉我$textArr[$i] 是什么吗?你能呼应吗?或者只是给出示例数据
  • 我的代码是垃圾。这是给菜鸟的。无论如何,我已经接受了 RichGold 的解决方案,它对我有用。谢谢!

标签: php newline fwrite


【解决方案1】:

根据您的系统,您的行可能不会以 \r\n 组合结尾,而可能只是 \r。

我建议将 str_replace 更改为:

$textAr[$i] = str_replace(array("\r","\n"),"", $textAr[$i]);

或者,改变数组:

$finalArray = array(trim($textAr[$i]), $m1, $m2, $m3, $m4, $m5, $m6);

顺便说一句,虽然它会起作用,但你的内爆参数是相反的:

$test = implode("***", $finalArray);

【讨论】:

  • 我已经添加了修剪,就像你说的那样,效果很好。谢谢!
【解决方案2】:

您应该使用 PHP_EOL 常量作为“换行符”字符。因为DOS中的换行符是\r\n,但在*nix中,它只是\n。 因此,您将第一行替换为

$textAr[$i] = str_replace(PHP_EOL, '', $textAr[$i]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-11
    • 2011-03-09
    • 2011-05-10
    • 1970-01-01
    • 1970-01-01
    • 2018-03-24
    相关资源
    最近更新 更多