PHP写入新行

时间:2022-09-29 12:41:00

I tried use file_put_contents output new page. but I meet some trouble in breaking new line.

我尝试使用file_put_contents输出新页面。但是我在打破新线路时遇到了一些麻烦。

<?php
$data ='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\r\n';
$data .='<html xmlns="http://www.w3.org/1999/xhtml" lang="en">\r\n';
$data .='<head>\r\n';
$data .='</head>\r\n';
$data .='<body>\r\n';
$data .='<p>put something here</p>\r\n';
$data .='</body>\r\n';
$data .='</html>\r\n';
file_put_contents( dirname(__FILE__) . '/new.php', $data);
?>

I tried \n or \r\n, they all can not make a new line:

我试过了\n或\r\n,它们都不能构成新的线条:

1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\r\n<html xmlns="http://www.w3.org/1999/xhtml" lang="en">\r\n<head>\r\n</head>\r\n<body>\r\n<p>put something here</p>\r\n</body>\r\n</html>\r\n

2 个解决方案

#1


29  

Using \r or \n in single quotes carries it literally. use double quotes instead like "\r\n"

在单引号中使用\r或\n可以实现它。使用双引号,比如“\r\n”

So one line might become:

所以有一行可能是:

$data .= "<head>\r\n";

or

$data .='<head>' . "\r\n";

#2


5  

You are using single-quoted character literals, which don't interpret escape sequences.
Either switch to double-quoted strings or, preferably, use heredoc syntax.

您使用的是单引号字符文字,它不解释转义序列。要么切换到双引号字符串,或者最好是使用heredoc语法。

<?php
$data = <<<CONTENTS
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org    /TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
</head>
<body>
<p>put something here</p>
</body>
</html>
CONTENTS;
file_put_contents( dirname(__FILE__) . '/new.php', $data);
?>

But really, why are you writing a hard-coded file? That's really strange.

但是,你为什么要写硬编码文件呢?这真的很奇怪。

#1


29  

Using \r or \n in single quotes carries it literally. use double quotes instead like "\r\n"

在单引号中使用\r或\n可以实现它。使用双引号,比如“\r\n”

So one line might become:

所以有一行可能是:

$data .= "<head>\r\n";

or

$data .='<head>' . "\r\n";

#2


5  

You are using single-quoted character literals, which don't interpret escape sequences.
Either switch to double-quoted strings or, preferably, use heredoc syntax.

您使用的是单引号字符文字,它不解释转义序列。要么切换到双引号字符串,或者最好是使用heredoc语法。

<?php
$data = <<<CONTENTS
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org    /TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
</head>
<body>
<p>put something here</p>
</body>
</html>
CONTENTS;
file_put_contents( dirname(__FILE__) . '/new.php', $data);
?>

But really, why are you writing a hard-coded file? That's really strange.

但是,你为什么要写硬编码文件呢?这真的很奇怪。