How can I add line breaks in php?

Avatar
  • Answered
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.

Avatar
BradM
Hi SteveC, Why is this happening? 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 <br /> to the screen instead of \n. For example, your php code may print the following:
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:
This ismy test stringwith new lines in it
To resolve this issue: To help resolve this issue, you can use PHP to either: 1. Replace all instances of \n with
2. Use PHP's built in nl2br function to insert HTML line breaks before all newlines. Why is this working on your own server? 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 <pre> 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. Thanks! - Brad