Not getting a new line when using use "\n" in PHP - php

I am trying to use \n in PHP to get a new line on my website, but it's not working.
Here is my code:
if(isset($_POST['selected'])){
$selected_val = $_POST['selected'];
// Storing Selected Value In Variable
echo "\n";
echo $selected_val; // Displaying Selected Value
}

On echo, use <br />.
The \n won't work in the HTML page, only in the source code, executing the PHP from the command line or writing into a text file.

This essentially boils down to saving the below text to a HTML file and expecting it to have visual line breaks:
one line
another line
To have a visual line break in HTML you're gonna need the br element:
one line<br />
another line
So replace your echo "\n"; with echo '<br />';.
If you have a string containing newlines, you could use the php built in nl2br to do the work for you:
<?php
$string = 'one line' . "\n" . 'another line';
echo nl2br($string);

When writing PHP code, you need to distinguish between two distinct concepts :
go to the new line in the code you produce, which you do using "\n"
go to the new line in the HTML webpage you produce, which you do using <br />
So, Option 1 makes you go to the new line in the code you produce, but you will not go to a new line in the HTML webpage you produce. The same way, option 2 makes you go to the new line in the HTML webpage you produce, but you will not go to a new line in the code you produce.
If you want go to the next line in both your code and the HTML output, you can just combine "\n" and <br /> :
echo "<br />\n";

On a web page, out of a <pre> block, all occurrences of tabs and newlines characters are assimilated as a single space.
For example:
echo "<pre>\n" . $selected_val . "</pre>";
But if your code is for debugging purposes, you'd better use print_r to inspect your variable values. Such as:
echo "<pre>" . htmlspecialchars(print_r($select_val), true) . "</pre>";
The htmlspecialchars function preserving you from ill-formed HTML due to the variable content.

Related

Tired of guessing - cannot get line break to work

VERY simple routine that pulls the name of each PDF file in a folder and creates a list of each file found with a link to it. But I cannot get a line break between the items
Nothing seems to give me each file name and link on a new line. I have no idea why.
Neither of the \n has any affect at all.
<?php
$directory = "./images/";
$phpfiles = glob($directory . "*.pdf");
foreach($phpfiles as $phpfile)
{
echo "\n","<a href=$phpfile>".basename($phpfile)."</a>";
echo "\n";
}
?>
All I get for output is this....all on one line.
CAD_REPEQUEST.pdf JP_CADS.pdf JP_Reports.pdf
What I want is this....
CAD_REPEQUEST.pdf
JP_CADS.pdf
JP_Reports.pdf
If you're outputting to a Web page you'll need to replace \n with <br>.
If you're outputting to a text or other type of file, you may wish to replace \n with the constant PHP_EOL.
If you're outputting this to an email that's getting sent in text format, you'll have trouble with some clients, like Outlook, that will automatically attempt to remove unnecessary line breaks. Sometimes using a double line break helps, or you could convert your email to HTML and use the <br> approach.

The proper use of PHP_EOL and how to get rid of character count when reading a file

I am trying to write a function in which a string of text is written with timestamps to the file "text2.txt", I want each entry to be on a new line, but PHP_EOL does not seem to work for me.The strings simply write on the same line and does not write to a new line for each string.
Could anyone give me some pointers or ideas as to how to force the script to write to a new line every time the function is activated?
Some sort of example would be highly appreciated.
Thank you in advance.
<?php
if($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['sendmsg']))
{
writemsg();
}
function writemsg()
{
$txt = $_POST['tbox'];
$file = 'text2.txt';
$str = date("Y/m/d H:i:s",time()) . ":" . $txt;
file_put_contents($file, $str . PHP_EOL , FILE_APPEND );
header("Refresh:0");
}
?>
Also, I want to get rid of the character count on the end of the string when using the below code :
<?php
echo readfile("text2.txt");
?>
Is there any way for the character count to be disabled or another way to read the text file so it does not show the character count?
Could anyone give me some pointers or ideas as to how to force the script to write to a new line every time the function is activated? Some sort of example would be highly appreciated.
Given the code you posted I'm pretty sure newlines are properly appended to the text lines you are writing to the file.
Try opening the file text2.txt on a text editor to have a definitive confirmation.
Note that if you insert text2.txt as part of a HTML document newlines won't cause a line break in the rendered HTML by the browser.
You have to turn them into line break tags <br/>.
In order to do that simply
<?php
echo nl2br( file_get_contents( "text2.txt" ) );
?>
Using file_get_contents will also solve your issue with the characters count display.
A note about readfile you (mis)used in the code in your answer.
Accordind to the documentation
Reads a file and writes it to the output buffer.
[...]
Returns the number of bytes read from the file. If an error occurs, FALSE is returned and unless the function was called as #readfile(), an error message is printed.
As readfile reads a file and sends the contents to the output buffer you would have:
$bytes_read = readfile( "text2.txt" );
Without the echo.
But in your case you need to operate on the contents of the file (replacing line breaks with their equivalent html tags) so using file_get_contents is more suitable.
To put new line in text simply put "\r\n" (must be in double quotes).
Please note that if you try to read this file and output to HTML, all new line (no matter what combination) will be replaced to simple space, because new line in HTML is <br/>. Use nl2br($text) to convert new lines to <br/>'s.
For reading file use file_get_contents($file);

Printing from PHP with correct line breaks

My code works, but I'm having trouble with line breaks...
I have data saved to a variable as such within a foreach loop:
$printerdata .= " " . $product_name . "\n";
$printerdata .= " $". $price . ".00 \n";
$printerdata .= " " . $displayoptions . "\n";
$printerdata .= "\n";
Then I post that data and use sockets to print to the printer from my php code. Like I said before, my code works great, but the problem lies with line breaks. When printed from one browser the data is displayed correctly with "\n" from the code above, however, when printed from the browser I'm being forced to use called Fresco, I get whitespace between the data rather than line breaks.
I've tried "\r\n" and that still does not produce any line breaks. I've also tried <br> but is literally printed out. Does anyone have any ideas on other ways to produce line breaks within my code? Thanks for the help!
The php function nl2br could help you. This function inserts HTML line breaks before all newlines in a string. You can look it up here:
nl2br Manual
The correct tag is
</br> not <br>
But I think in fresco there is also a tag
<af>

Printing contents of array on separate lines

Experimenting with arrays and wondering why the following DOESN'T seem to print the values on SEPARATE lines when I run it?
<?php
$my_array = array("stuff1", "stuff2", "stuff3");
echo $my_array[0] . "\n";
echo $my_array[1] . "\n";
echo $my_array[2] . "\n";
?>
This makes the trick.
<?php
$my_array = array("stuff1", "stuff2", "stuff3");
foreach ( $my_array as $item ) {
echo $item . "<br/>";
}
?>
If your viewing the output in a web browser, newlines aren't represented visually. Instead you can use HTML breaks:
<?php
$my_array = array("stuff1", "stuff2", "stuff3");
echo implode('<br>', $my_array);
?>
From my PHP textbook:
One mistake often made by new php programmers (especially those from a
C background) is to try to break lines of text in their browsers by
putting end-of-line characters (“\n”) in the strings they print. To
understand why this doesn’t work, you have to distinguish the output
of php (which is usually HTML code, ready to be sent over the
Internet to a browser program) from the way that output is rendered
by the user’s browser. Most browser programs will make their own
choices about how to split up lines in HTML text, unless you force a
line break with the <BR> tag. End-of-line characters in strings will
put line breaks in the HTML source that php sends to your user’s
browser (which can still be useful for creating readable HTML
source), but they will usually have no effect on the way that text
looks in a Web page.
The <br> tag is interpreted correctly by all browsers, whereas the \n will generally only affect the source code and make it more readable.
You need to print with <br/> instead of \n because the default PHP mime type is HTML, and you use <br/> to accomplish line breaks in HTML.
For example,
<?php
$my_array = array("stuff1", "stuff2", "stuff3");
echo $my_array[0] . "<br/>";
echo $my_array[1] . "<br/>";
echo $my_array[2] . "<br/>";
?>
That's because in HTML a line break is <br />, not "\n".

New Line Character in PHP script on Remote Server not working

I am having trouble with "\n" character not working. I realized that it wasn't work while testing output of variables using a simple echo statement. I have tried approaching the new line character a few different ways to see if it was just me, but nothing I have tried is working. Here is an example of some attempts I have made:
<?php
// Establish Connection to Taskaro DB
require "../_connections/connection_taskDB.php";
// Start Session
session_start();
// Create Session Variables
$_SESSION['userID'];
$_SESSION['companyID'];
$_SESSION['usernameDB'];
// Convert Session Variables to page variables
$userID = $_SESSION['userID'];
$currentUser = $_SESSION['usernameDB'];
$editType = $_REQUEST['editType'];
$projectID = $_REQUEST['projectID'];
// Testing if new line character is working
echo "hello, Mr. New Line!\n\r";
echo "This line should be below 'hello, Mr. New Line!'";
// Testing variable and session connection
echo "SESSION VARIABLES:"."\\n\n"."userID = {$userID}";
echo "userID = {$userID}"."/n";
echo "currentUser = {$currentUser}"."\r";
echo "companyID = {$companyID}\n\r";
echo "\nPOST VARIABLES:\n";
echo "editType = {$editType}\n";
echo "projectID = {$projectID}\n";
?>
I read up on some other overflow questions that had similar problems and none of them fixed my problem. The project is on a remote server (GoDaddy) in which php has been installed. The document has the correct file extension (.php). I am coding in dreamweaver and uploading my script for testing. From the code you can see I've tried "\n","\n\r","\r". I've also tested in both Firefox and Google Chrome.
I also tried to concatenate the "\n" character, and took a shot in the dark and even tried using the forward slash rather than the backslash (I knew it wouldn't work, but I'm getting pretty frustrated at this point). I bet it's something simple but I don't see what else is could be. Thanks in advanced.
If you view the source of the page, you will see all of those values output on separate lines.
If you are viewing the file in the browser, you need to use line breaks (<br />) if you want your text to show up on different lines. HTML ignores newlines in regards to presentation.
echo "hello, Mr. New Line!\n";
echo "This line should be below 'hello, Mr. New Line!'";
When viewing source, the above two text strings will be on separate lines. When viewed in the browser they will appear to be on the same line.
echo "hello, Mr. New Line!\n<br />";
echo "This line should be below 'hello, Mr. New Line!'";
When viewing source, the above two text strings will be on separate lines because of the \n. When viewed in the browser they will also be on separate lines because of the HTML break <br />.
Use the PHP_EOL constant instead of \n and call it a day.
Also, it's \r\n, not the other way around.
If you are expecting the browser to render new line characters as new lines in HTML, that won't happen. You need to use the <br> tag.

Categories