Php 如何按原样写入文件?

Php 如何按原样写入文件?,php,newline,Php,Newline,我有一个如下的代码字符串: <?php echo "Hello World"; ?> 此代码在我的电脑上运行。您也会喜欢它的 <?php $file = 'people.php'; // The new person to add to the file $person = "<?php echo 'Hello World'; ?>\n"; // Write the contents to the file, // using the FILE_APPEND f

我有一个如下的代码字符串:

<?php
echo "Hello World";
?>

此代码在我的电脑上运行。您也会喜欢它的

<?php
$file = 'people.php';
// The new person to add to the file
$person = "<?php
echo 'Hello World';
?>\n";
// Write the contents to the file, 
// using the FILE_APPEND flag to append the content to the end of the file
// and the LOCK_EX flag to prevent anyone else writing to the file at the same time
file_put_contents($file, $person, FILE_APPEND | LOCK_EX);
echo $person;
?>

尝试在每行代码之间使用以下命令将其放在php文件的新行上:

 . PHP_EOL .
你可以:

<?php
$yourContent = <<<PHP
<?php
 echo "Hello world";
 echo "This in an example";
 $foo = 2;
 $bar = 4;
 echo "Foo + Bar = ".($foo+$bar);
?>
PHP;
file_put_contents("yourFile.php", $yourContent);
?>

PHP;
文件内容(yourFile.php,$yourContent);
?>

您的字符串应该是这样的

$str = "<?php
echo \"Hello World\";
?>";
$str=”“;
然后将其写入任意fileName.php,php在解析时忽略新行,只有分号起作用

编辑1

由于您希望以代码的形式编写字符串,在完成上述步骤后,您的所有代码都将放在一行中,更像是一个压缩代码,这将是不可读的,为了使其更人性化,您必须添加格式,一种最简单的格式设置方法是至少添加新行字符和缩进制表符


为此,您必须做两件事,确定需要添加新行馈送的字符(a)和需要缩进的字符(b)。现在,在写入文件之前,先做一些预处理,为字符类型(a)添加新行字符,同时维护一个堆栈,以便为缩进添加适当数量的制表符

使用heredoc时,这应该可以正常工作:

file_put_contents('people.php', <<<HEREDOC
<?php
echo "Hello World";
?>
HEREDOC
);
file\u put\u contents('people.php',尝试以下内容:

<?php
$file = "helloworld.php";
$content = file_get_contents($file);
print_r(htmlspecialchars($content));
?>

Helloworld.php

<?php
echo "Hello World";
?>


它可以正常工作。

听起来您需要在每行末尾添加换行符。您可以使用正则表达式搜索/替换,如下所示(其中$newData已经包含要附加到文件中的字符串):



这将查找每行的结尾(在正则表达式中用$表示),并添加新行(\n)在那个位置。

我不明白,你期望的输出是什么?会发生什么?你想完成什么?也许问题在于编辑器,而不是你的代码?就像很多人说的,你需要一个
\n
来获得一行新行。你在使用什么编辑器?你想把一个PHP文件复制到另一个吗?(如果是,请使用)。[或者您希望通过web向用户输出内容吗?]哈!这很简单!!!!!如果此代码更改为@SanjayRathod怎么办Bhadra想说的是,当您写入文件时,字符串中的行刹车需要
\n
转义字符。但是我从编辑器中获取此代码,每次代码都不同,那么我如何生成新的行字符?检查这里。在这个编辑器中,用户可以添加执行代码。很明显,每次都不一样,因此如何插入新行字符。此奖励将在4小时后到期,您已将此答案标记为正确。我有一个更好的答案。如果您联机,请在此处ping,我会将其挂起。这不是通用解决方案。
<?php
$file = "helloworld.php";
$content = file_get_contents($file);
print_r(htmlspecialchars($content));
?>
<?php
echo "Hello World";
?>
<?php
$newData = preg_replace('/$/',"\n", $newData);
file_put_contents($file, $newData, FILE_APPEND | LOCK_EX);
?>