Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Initiate Variable With Multiple Lines

I know I can make a new variable by simply saying $var = "stuff", but how would I make one like this:

<?php
$var = ?>
<html>
<head>
</head>
<body>
</body>
</html>
<? ; ?>

Do you see what I am getting at? Is there a way to create a variable without having to be restrictive and using = "";

Thanks for your help.

like image 801
Gray Adams Avatar asked Jan 19 '12 22:01

Gray Adams


People also ask

What is EOD PHP?

EOD = End Of Data, EOT = End of Text.

How strings are declared in PHP explain string operators?

We can create a string in PHP by enclosing the text in a single-quote. It is the easiest way to specify string in PHP. For specifying a literal single quote, escape it with a backslash (\) and to specify a literal backslash (\) use double backslash (\\).

Which escape sequences can be used in single quoted strings in PHP?

Escape Sequences In PHP, an escape sequence starts with a backslash \ . Escape sequences apply to double-quoted strings. A single-quoted string only uses the escape sequences for a single quote or a backslash.


2 Answers

Sounds like a job for Heredoc

$var = <<<HTML
<html>
<head>
</head>
<body>
</body>
</html>
HTML;

Note, that the end token (here HTML;) must be on a line for itself without any leading or trailing whitespaces (except the newline at the end).

Additional you can just put everything into a string like usual, but with newlines

$var = '<html>
<head>
</head>
<body>
</body>
</html>';

Or add newline characters yourself

$var = '<html>' . PHP_EOL;
$var .= '<head>' . PHP_EOL;
$var .= '</head>' . PHP_EOL;
$var .= '<body>' . PHP_EOL;
$var .= '</body>' . PHP_EOL;
$var .= '</html>';

or

$var = "<html>\n<head>\n</head>\n<body>\n</body>\n</html>";
like image 137
KingCrunch Avatar answered Sep 26 '22 11:09

KingCrunch


If you want to parse PHP variables (like you would with a double quote), use the HEREDOC syntax.

If you want no parsing of variables, use the NOWDOC syntax.

like image 27
AndrewR Avatar answered Sep 22 '22 11:09

AndrewR