Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP new line \n and \r\n not working

  $rows = mysql_num_rows($result) ;
  for ($j=0 ; $j < 3 ; $j++) {
  for ($i=0 ; $i < 3 ; $i++) {
    $row = mysql_fetch_array($result) ;
    echo '<a href="image2.php?id='.$row['ID'].'">'."<img src='".$row['Image']."' />".'</a>' ;

  }
   echo "\r\n";
  }

The code displays three groups of three images. My understanding was that \r\n and \n (double quotes) should create a new line. However it is just inserting a space between the images. Is the way am callign \r\n wrong or is it am using the wrong code to isneert a new line (line break)

Examples (# = one image):

Without echo \r\n: ######### With echo \r\n: ### ### ###

like image 885
Dan1676 Avatar asked Apr 26 '12 10:04

Dan1676


People also ask

Does \n work in PHP?

You can use the PHP newline characters \n or \r\n to create a new line inside the source code. However, if you want the line breaks to be visible in the browser too, you can use the PHP nl2br() function which inserts HTML line breaks before all newlines in a string.

Is it n or \n for new line?

Operating systems have special characters denoting the start of a new line. For example, in Linux a new line is denoted by “\n”, also called a Line Feed. In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF.

How do I add a new line to a string in PHP?

The nl2br() function inserts HTML line breaks (<br> or <br />) in front of each newline (\n) in a string.


4 Answers

Your echo "\r\n"; is outside the loop. Move it inside the loop.

Also, if you want the line breaks to be visible in the browser, you should print a <br /> too.

  $rows = mysql_num_rows($result) ;
  for ($j=0 ; $j < 3 ; $j++) {
  for ($i=0 ; $i < 3 ; $i++) {
    $row = mysql_fetch_array($result) ;
    echo '<a href="image2.php?id='.$row['ID'].'">'."<img src='".$row['Image']."' />".'</a>' ;
  }
    echo "<br />\n";    
  }
like image 157
Nadh Avatar answered Oct 05 '22 07:10

Nadh


Whitespace is not displayed verbatim when it's part of HTML text. \r and \n are not universal constants; they are just characters, and it's up to whatever program consumes them to decide what to do with them.

You should use <br> instead.

like image 33
Jon Avatar answered Oct 05 '22 07:10

Jon


You need:

echo '<br />';

instead of:

echo "\r\n";
like image 31
codaddict Avatar answered Oct 05 '22 07:10

codaddict


You can also consider setting a proper header Exmaple:


$data = [
    [1,2,3],
    [4,5,6],
    [7,8,9]
];
header("Content-Type: text/plain");
foreach($data as $row){
    echo implode(',', $row) . "\r\n";
}

like image 20
Emeka Mbah Avatar answered Oct 05 '22 07:10

Emeka Mbah