Gavin Pedley
Gavin Pedley

Reputation: 51

How to add a new line/linebreak in php code

i am wondering if someone can help me. I know html more than php.

I need to put a line break after each part of the address string here.

<?php echo $this->get_detail($order, 'address_1');?>
<?php
$address2 = $this->get_detail($order, 'address_2');
$country = $this->get_detail($order, 'country');
if (!empty($address2)) echo ", ".$this->get_detail($order, 'address_2');
?>
, <?php echo $this->get_detail($order, 'city');?>, <?php echo $this- 
>get_detail($order, 'state');?>, <?php echo $this->get_detail($order, 
'postcode'); ?> <?php
if ($country) echo ", ".$country;   
?>

So new line after address1, new line after address 2 etc How can i do this? I have read about \n but don't know where to put it.

Also i want to put a line space above and below the title "customer note:" that this produces

$customer_note = is_callable(array($order, 'get_customer_note')) ? $order- 
>get_customer_note() : $order->customer_note;
if ($customer_note) {
echo __('Customer Note:', 'woocommerce').' '.$customer_note."\n";
}

Again i am not sure how to best do this. Any help would be very very welcome.

So what both codes above produce at the moment is:

House number and street, town, county, postcode , country Customer Note: this is the customer note blah blah blah.....

What i want it to look like is this:

House number and street
town
county
postcode
country


Customer Note:


this is the customer note blah blah blah.....

Upvotes: 1

Views: 11146

Answers (2)

Diego Avila
Diego Avila

Reputation: 738

Newlines in HTML are expressed through <br>, not through \n. example:

<?php
  echo"Fo\n";
  echo"Pro";
?>

output

Fo
Pro

or you can use this:

<?php
  echo"Fo";
  echo"<br>";/* this print new line*/
  echo "pro";
?>

Upvotes: 1

Rubin Gajera
Rubin Gajera

Reputation: 87

\n is a line break.


use of \n with

1. echo directly to page

Now if you are trying to echo string to the page:

echo  "kings \n garden";

output will be:

kings garden

you won't get garden in new line because PHP is a server-side language, and you are sending output as HTML, you need to create line breaks in HTML. HTML doesn't understand \n. You need to use the nl2br() function for that.

What it does is:

Returns string with <br /> or <br> inserted before all newlines (\r\n, \n\r, \n and \r).

echo  nl2br ("kings \n garden");

Output

kings
garden

Note Make sure you're echoing/printing \n in double quotes, else it will be rendered literally as \n. because php interpreter parse string in single quote with concept of as is

so "\n" not '\n'

2. write to text file

Now if you echo to text file you can use just \n and it will echo to a new line, like:

$myfile = fopen("test.txt", "w+")  ;

$txt = "kings \n garden";
fwrite($myfile, $txt);
fclose($myfile);
 

output will be:

kings
 garden

Upvotes: 4

Related Questions