Multi-line strings in PHP

Multi-line strings in PHP

Well,

$xml = l
vv;

Works.

You can also use the following:

$xml = lnvv;

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;

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 doesnt replace variables.

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

You dont 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 wont 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.

Multi-line strings in PHP

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

$text=line1rn .
      line2rn .
      line3rn;

It also lets me indent however I want.

Leave a Reply

Your email address will not be published.