在 fwrite 时忽略 PHP 中的转义序列


Ignore escape sequences in PHP while fwrite

有没有办法在使用fwrite时忽略像''n'这样的字符并按文件中的原样打印它们?

$x = "Some data with 'nslash n";
fwrite($fp, $x."'r'n");
Gives me : 
Some data with
slash n

我知道使用单引号可以解决我的问题,但$x来自其他地方,因此它的值已经设置好了。

如果仅转义换行符,请将 PHP_EOL 常量追加到字符串中,就在要换行符的位置。所以例如:

$x = "Some data with".PHP_EOL."slash n";

我有一个不好的答案,但也许它会有所帮助:

fputs($fp, str_replace(["'r","'n"],["''r","''n"],$x."'r'n")."'n");

窍在于双引号和单引号

在str_replace中搜索时使用双引号,在放回值时使用单引号

要替换文件并将其下载到PC,以下是代码:

<?php
    $a = "My Name'n is Ashwani";
    $b = str_replace("'n",''n',$a);
    header('Content-disposition: attachment; filename=output.txt');
    header('Content-type: text/plain');
    echo "This is the original data:'n".$a;
    echo "'n'n'nThis is the replaced data:'n".$b;
?>

要在服务器上写入具有输出和扩展名 csv 的文件,代码如下:

<?php
    $a = "My Name'n is Ashwani";
    $b = str_replace("'n",''n',$a);
    $h = fopen("output.csv","w");
    fwrite($h,"This is the original data:'n".$a);
    fwrite($h,"'n'n'nThis is the replaced data:'n".$b);
    fclose($h);
?>

希望这有帮助