Can't get \n or \r command to work

Need help installing PHP, configuring a script, or configuring a server? Then come on in and post your questions! We'll try to help the best we can!

Moderator: General Moderators

Post Reply
RConf
Forum Newbie
Posts: 2
Joined: Thu Feb 12, 2009 5:31 pm
Location: Australia

Can't get \n or \r command to work

Post by RConf »

Sorry if this one's a waste of time, I've done a search for a similar question - I'm a complete novice and I've just finished configuring my first WAMP test site. Working through a tutorial, I thought I had covered all the general php.ini setup issues, however when running simple test code:

<?php

// sample text here

$output = "This is one line.\n And this is another line.";
echo $output;

?>

...returns this in the browser (next line and carriage return characters don't work):

This is one line. And this is another line.

Have I missed something in my configuration?
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: Can't get \n or \r command to work

Post by John Cartwright »

Code: Select all

$output = "This is one line.\n And this is another line.";
echo nl2br($output);
:)
User avatar
Eran
DevNet Master
Posts: 3549
Joined: Fri Jan 18, 2008 12:36 am
Location: Israel, ME

Re: Can't get \n or \r command to work

Post by Eran »

This is not a PHP issue. Your browser reads output as HTML, which does not respect newlines (those are used for source code formatting) but only line-break tags (<br />).

You can convert the string to line-breaks using ln2br()

Code: Select all

$output = "This is one line.\n And this is another line."; 
echo nl2br($output);
Or use the white-space CSS attributre (pre-wrap).

http://www.php.net/nl2br
http://developer.mozilla.org/en/CSS/white-space
RConf
Forum Newbie
Posts: 2
Joined: Thu Feb 12, 2009 5:31 pm
Location: Australia

Re: Can't get \n or \r command to work

Post by RConf »

I have much to learn.

Many thanks.
Post Reply