Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add line-break in text/plain email

I’m using the function of WordPress wp_mail() to send an email about the form data that is submitted on my website.

In the $data, I have tried to use \n for line break but it printed \n on the email like below:

First value \n Second value \n Third Value

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My code is:

$data = "First: $first_value" . '\n' . "Second: $second_value" . '\n' . "Third: $third_value"

The desired result in the email received is:

First: value

Second: value

Third: value

>Solution :

To ensure that the break lines ("\n") are implemented appropriately, as M.Eriksson suggested, you must avoid single quatations when defining them. To be more clear, see the output of the code below:

$first_value = "one";
$second_value = "second";
$third_value = "third";
$data = "First: $first_value" . '\n' . "Second: $second_value" . '\n' . "Third: $third_value";
echo($data);
First: one\nSecond: second\nThird: third

But when you use double quotation (") instead of single quotation (‘) the result would be:

<?php
$first_value = "one";
$second_value = "second";
$third_value = "third";
$data = "First: $first_value" . "\n" . "Second: $second_value" . "\n" . "Third: $third_value";
echo($data);
?>
First: one
Second: second
Third: third

A more generic approach would be using PHP_EOL:

<?php
$first_value = "one";
$second_value = "second";
$third_value = "third";
$data = "First: $first_value" . PHP_EOL . "Second: $second_value" . PHP_EOL . "Third: $third_value";
echo($data);
?>
First: one
Second: second
Third: third
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading