Multi-line strings in PHP

Multi-line strings in PHP


$xml = l


You can also use the following:

$xml = lnvv;


$xml = <<<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.

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

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.

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 .

It also lets me indent however I want.

Leave a Reply

Your email address will not be published.