How to read a text file into PHP with set format?

My text file:

user@example.com
user1@example.com
user2@example.com
user3@example.com
user4@example.com
user5@example.com
...

How do I add the text file to my PHP file like this:
'user@example.com', 'user1@example.com'

<?php 
function nl2br2($text){
    return preg_replace("/\r\n|\n|\r/", "<br>", $text);
}
$str= file_get_contents("sheet5.txt");
echo nl2br2($str);
?>

This page / code keeps running, how to make it stop at the end of the file?

Recommended Answers

All 8 Replies

Try the while loop.

while($str = file_get_contents("sheet5.txt")) {
     echo nl2br($str);
}

No that doesn't work, kills my PC as well.

This works, but without the format;

$str = file("sheet5.txt");
foreach($str as $line){
   echo nl2br($line);
}

you have to put the formatting in, something like

echo "'";
$str = file("sheet5.txt");
foreach($str as $line){ echo nl2br($line)."','"; }

you have to put the formatting in, something like

Almost perfect excpet the last ,'

This only leaves one comma at the end?

$lines = file('sheet5.txt');
foreach ($lines as $line_num => $line)  {
	print "'".$line."', ";
}

Now to remove commas? it never ends...

Try below to remove comma at the end

$str="rolling,";
echo substr($str,0,strlen($str)-1);

Try below to remove comma at the end

$str="rolling,";
echo substr($str,0,strlen($str)-1);

How would your snippet work?
I just woke up and may be a bit sleepy still.

Hi json101,

Sureronald's snippet removes the last character of a string $str by copying all characters of the string in the range [0, length-1].

In your snippet above, the last character is a space and the second last character is the comma you wish to remove. So using Sureronald's snippet you need to remove an extra character from the end.

Also Sureronald's script assumes that you are storing the text contents in a string so that it can be manipulated before it is output to the browser/console. In your snippet you are outputting to the browser/console immediately and consequently the comma can't be removed because it's already been sent.

The snippet below solves both these problems mentioned above.

$lines = file('sheet5.txt');
$str = '';
foreach ($lines as $line_num => $line)  {
	str .=  "'".$line."', ";
}
$str = substr($str,0,strlen($str)-2); // or you could use: $str = rtrim($str, ', ');
echo $output;

Hope this helps,

James

A few edits in red, but yes that also works.

$lines = file('sheet1.txt');
$str = '';
foreach ($lines as $line_num => $line)  {
	$str .=  "'".$line."', ";
}
$str = substr($str,0,strlen($str)-2); // or you could use: $str = rtrim($str, ', ');
echo $str;
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.