Multi-line strings in PHP

Consider:

$xml = "l";
$xml = "vv";

echo $xml;

This will echo vv. Why and how can I do multi-line strings for things like SimpleXML, etc.?


Solution 1:

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";

Solution 2:

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.

Solution 3:

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.

Solution 4:

$xml="l" . PHP_EOL;
$xml.="vv";
echo $xml;

Will echo:

l
vv

Documentation on PHP_EOL.