InMotion Hosting Support Center

How can I add line breaks in php?

2012-02-09 6:04 pm EST

Hits: 64,717
My php cgi code includes writing out strings with "\n" at the end; I thought this would give me a new line, but that isn't happening. I am just getting one continuous string. I also tried "\n\r" but that did not make a difference.

Works on my mainframe server.

You must login before you can ask a follow up question.

You must login before you can submit an answer.



5,399 Points
2012-02-09 6:19 pm EST
Hi SteveC,

<strong>Why is this happening?</strong>

When you use PHP to print a new line using \n, it does print a newline to the screen. The problem is that if you want to add a line break in PHP, you'll need to print &lt;br /&gt; to the screen instead of \n.

For example, your php code may print the following:
<div class='code_block'>This is

my test string

with new lines in it

A web browser will not automatically add line breaks however to lines. The above code when viewed in a browser will look like:

<div class='code_block'>This ismy test stringwith new lines in it</div>

<strong>To resolve this issue:</strong>

To help resolve this issue, you can use PHP to either:

1. <a href='' target='_blank'>Replace</a> all instances of \n with <br />

2. Use PHP's built in <a href='' target='_blank'>nl2br function</a> to insert HTML line breaks before all newlines.

<strong>Why is this working on your own server?</strong>

I can't say for sure why this works on your mainframe server without having more details. The first thing I would do is view the html source code on your mainframe server and check to see if you have some setup that automatically adds line breaks to your code. Also, you may be using the &lt;pre&gt; tag to output your text, and in that case, the new lines (\n) will print as you are expecting.

If you have any further questions, feel free to update your question or post in the comments, and I'll be happy to assist further.

- Brad

You must login before you can post a comment about this answer.

Like this Question?

Forum Login

You are NOT logged in. You can still browse our Support Center.

To participate within our Community Support Forum:

Need more Help?

Ask the Community!

Get help with your questions from our community of like-minded hosting users and InMotion Hosting Staff.

Current Customers

Chat: Click to Chat Now E-mail:
Call: 888-321-HOST (4678) Ticket: Submit a Support Ticket

Not a Customer?

Get web hosting from a company that is here to help. Sign up today!