Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi-line strings in PHP

Tags:

string

php

People also ask

How to write multi line strings in PHP?

Writing \n or \r\n inside your strings will give you new lines in PHP. This allows you to easily create multiline characters.

How to echo multiple lines PHP?

The \n escape sequences can be used to declare multiple lines in a string.

What is EOT PHP?

So, for example, we could use the string EOT (end of text) for our delimiter, meaning that we can use double quotes and single quotes freely within the body of the text—the string only ends when we type EOT .

How many types of strings are there in PHP?

There are four ways of creating strings in PHP: 1. Single-quote strings: This type of string does not process special characters inside quotes.


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

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.


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.


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

Will echo:

l
vv

Documentation on PHP_EOL.


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.