Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP file_put_contents new line

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

<?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:

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
like image 383
fish man Avatar asked Jun 13 '11 23:06

fish man


2 Answers

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

So one line might become:

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

or

$data .='<head>' . "\r\n";
like image 159
Sabeen Malik Avatar answered Sep 24 '22 18:09

Sabeen Malik


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

<?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.

like image 25
Zecc Avatar answered Sep 23 '22 18:09

Zecc