[php] 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.?

This question is related to php string

The answer is


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

Will echo:

l
vv

Documentation on PHP_EOL.


Maybe try ".=" indead of "="?

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

will give you "lvv";


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;

Beware that the end token EOD must not be indented at all, or PHP won't acknowledge it. Also, you don't have to use "EOD"; it can be any string you want.


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.


To put the strings "l" and "vv" on separate lines in the code alone:

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

In this instance you're saying to append .= the string to the end of the previous version of that string variable. Remember that = is only an assignment operator so in your original code you're assigning the variable a new string value.

To put the strings "l" and "vv" on separate lines in the echo alone:

$xml = "l\nvv"
echo $xml;

You don't need multiple strings in this instance, as the new line character \n will take care of that for you.

To put the strings "l" and "vv" on separate lines in code and when echoing:

$xml = "l";
$xml .= "\nvv"
echo $xml;

Another solution is to use output buffering, you can collect everything that is being outputted/echoed and store it in a variable.

<?php
ob_start(); 

?>line1
line2
line3<?php 

$xml = ob_get_clean();

Please note that output buffering might not be the best solution in terms of performance and code cleanliness for this exact case but worth leaving it here for reference.


$xml="l\rn";
$xml.="vv";

echo $xml;

But you should really look into http://us3.php.net/simplexml