Multi-line strings in PHP

PHP has Heredoc and Nowdoc strings, which are the best way to handle multiline strings in PHP.

http://php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc

$str = <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
$var is replaced automatically.
EOD;

A Nowdoc is like a Heredoc, but it doesn't replace variables.

$str = <<<'EOD'
Example of string
spanning multiple lines
using nowdoc syntax.
$var is NOT replaced in a nowdoc.
EOD;

You don't have to use "EOD" as your start/end identifier; it can be any string you want.

Beware indentation. Prior to PHP 7.3, the end identifier EOD must not be indented at all or PHP won't acknowledge it. In PHP 7.3 and higher, EOD may be indented by spaces or tabs, in which case the indentation will be stripped from all lines in the heredoc/nowdoc string.


Well,

$xml = "l
vv";

Works.

You can also use the following:

$xml = "l\nvv";

or

$xml = <<<XML
l
vv
XML;

Edit based on comment:

You can concatenate strings using the .= operator.

$str = "Hello";
$str .= " World";
echo $str; //Will echo out "Hello World";

Not sure how it stacks up performance-wise, but for places where it doesn't really matter, I like this format because I can be sure it is using \r\n (CRLF) and not whatever format my PHP file happens to be saved in.

$text="line1\r\n" .
      "line2\r\n" .
      "line3\r\n";

It also lets me indent however I want.

Tags:

Php

String