Output text file with line breaks in PHP - php

I'm trying to open a text file and output its contents with the code below. The text file includes line breaks but when I echo the file its unformatted. How do I fix this?
Thanks.
<html>
<head>
</head>
<body>
$fh = fopen("filename.txt", 'r');
$pageText = fread($fh, 25000);
echo $pageText;
</body>
</html>

To convert the plain text line breaks to html line breaks, try this:
$fh = fopen("filename.txt", 'r');
$pageText = fread($fh, 25000);
echo nl2br($pageText);
Note the nl2br function wrapping the text.

One line of code:
echo nl2br( file_get_contents('file.txt') );

If you just want to show the output of the file within the HTML code formatted the same way it is in the text file you can wrap your echo statement with a pair of pre tags:
echo "<pre>" . $pageText . "</pre>;
Some of the other answers look promising depending on what you are trying todo.

For simple reads like this, I'd do something like this:
$fileContent = file_get_contents("filename.txt");
echo str_replace("\n","<br>",$fileContent);
This will take care of carriage return and output the text. Unless I'm writing to a file, I don't use fopen and related functions.
Hope this helps.

Before the echo, be sure to include
header('Content-Type: text/plain');

Are you outputting to HTML or plain text? If HTML try adding a <br> at the end of each line. e.g.
while (!feof($handle)) {
$buffer = fgets($handle, 4096); // Read a line.
echo "$buffer<br/>";
}

Trying to get line breaks to work reading a .txt file on Apache2 and PHP 5.3.3 with MacOSX 10.6.6 and Camino, the echo nl2br( $text); didn't work right until I printed the file size first too.
BTW it doesn't seem to matter if the .txt file has Linux/MacOSX LF or Windows CRLF line breaks or the text encoding is UTF-8 or Windows Latin1, Camino gets it out OK.
<?php
$filename = "/Users/Shared/Copies/refrain.txt";
$file_ptr = fopen ( $filename, "r" );
$file_size = filesize ( $filename );
$text = fread ( $file_ptr, $file_size );
fclose ( $file_ptr );
echo ( "File size : $file_size bytes<br> <br>" );
echo nl2br ( $text );
?>

You need to wrap your PHP code into <?php <YOU CODE HERE >?>, and save it as .php or .php5 (depends on your apache set up).

Say you have an index.php file hosted by the web server. You want to insert some multi-line text file contents into it. That's how you do it:
<body>
<div>Some multi-line message below:</div>
<div><?= nl2br(file_get_contents('message.txt.asc')); ?></div>
</body>
This <?= ... ?> part is just a shorthand, which instructs the web server, that it needs to be treated as a PHP echo argument.

Related

PHP include text file and format

I have a simple text file. The file name is kpop.txt - What I want to do is include the contents of the file in a webpage. I am using php for includes (header / footer stuff).
I would like the contents of the kpop.txt file to remain formatted similar to it's current form. The only real difference that I would like to make is to increase the font size.
I am currently using
<?php
include("kpop.txt");
?>
I have also tried
<pre>
<font size ="12">
<?php
include("kpop.txt");
?>
</font>
</pre>
What I want to see is my text like this but simply with a larger font.
FTUS43 KGGW 271140
TAF
KP01 271140Z 2706/2806 08010KT P6SM SCT140
FM271500 12011KT P6SM SCT110
FM271900 14011KT P6SM BKN120
FM280000 14008KT P6SM VCSH BKN100
FM280300 13006KT P6SM VCSH SCT100
AMD NOT SKED. UNFL=
TAF
KM75 271140Z 2706/2806 07008KT P6SM SCT110
FM271500 11008KT P6SM FEW150
AMD NOT SKED. UNFL=
Another solution that did not work is
<?php
myfilename = "kpop.txt";
$TAF = file_get_contents(myfilename);
$TAFlines = explode("\n", $TAF);
//echo $TAF;
echo $TAFlines;
}
?>
I have also tried using the file_get_contents function along with an explode function but cannot seem to get that to work properly. Any help is greatly appreciated.
So this is what I came up with.
<pre>
<?php
//Read in the file and increase the font 200%
$TAF = file_get_contents("kpop.txt");
echo "<div style='font-size:200%'><p>$TAF</p></div>";
?>
</pre>
It may not be pretty but it works. Thank you all for your help.
I would suggest you use CSS, rather than the deprecated <font> tag:
<pre style="font-size:120%">
<?php echo file_get_contents('kpop.txt') ?>
</pre>
It's pretty simple, use fopen() and then read it fread(),just use echo to display it:
<?php
$myfile = fopen("kpop.txt", "r") or die("Unable to open file!");
echo '<span style="font-size:30px;">' . fread($myfile,filesize("kpop.txt"))
. ' </span>';
fclose($myfile);
?>
More details: https://www.w3schools.com/php/php_file_open.asp

how to write a string to a file that contains html tags

I have created new .php file through php file system and now I am trying to write html code into file. Here is the code
$file = 'django unchained.php';
if($handle = fopen($file , 'a'))
{
$text = htmlentities("Just link");
echo $text; // here it shows up fine in webpage.
file_put_contents($file , $text); // after writing to file it doesnot appear the same in .php file
fclose($handle);
}
As mentioned in comment above when I echo it in webpage it shows up fine but doesnot appear the same when same string is written to file.
Thanks in advance.
If you open the source code of your HTML page, you'll see the same text, you see in django unchained.php:
<a href="index.php">Just link</a>
This text is generated by htmlentities function, that converts special HTML characters to their entity equivalents. This behaviour is absolutely predictable and correct.
If you want to output to file the unquoted text, do this:
<?php
$file = 'django unchained.php';
$text = "Just link";
echo htmlentities($text); // here it shows up fine in webpage.
file_put_contents($file , $text) or die('Error opening file');
Looks like you have problems with locks, try this code:
$file = 'django unchained.php';
$text = "Just link";
file_put_contents($file , $text) or die('Cannot open file for writing');
note: you do not need fopen, fclose, htmlspecialchars here

nl2br and str_replace not working in PHP script

I am saving and editing data in text files through a text area using CKeditor and everything is working smoothly. Everything except new lines ("<br />") that don't show when I try to edit/update the text file via my update.php. I really can't find out what is the issue, I have tried to replace tag after tag and did not manage to solve the problem.
Code for reading and writing on the text file:
$text1 = "../conteudos/start/text1.txt";
if (isset($_POST['body1'])) {
$newData = nl2br($_POST['body1']);
$handle = fopen($text1, "w");
fwrite($handle, $newData);
fclose($handle);
}
// ------------------------------------------------
if (file_exists($text1)) {
$myData1 = file_get_contents($text1);
$myData1 = strip_tags($myData1);
}
Code for editing the text contents:
<textarea class="ckeditor" name="body1" id="body1">
<?php echo str_replace("<br />","",$myData1); ?>
</textarea>
As mentioned before, the text shows up nicely on my index.php with no html tags whatsoever, but when I try to edit it via the text area above I still get no tags, but I get all the text into one single line. This really should be working because I am using "nl2br" function, but apparently something is canceling it.
What can I do?
I think what you are trying to do is:
$text1 = "../conteudos/start/text1.txt";
if (isset($_POST['body1'])) {
$newData = nl2br($_POST['body1']);
$handle = fopen($text1, "w");
fwrite($handle, $newData);
fclose($handle);
}
// ------------------------------------------------
if (file_exists($text1)) {
$myData1 = file_get_contents($text1);
//Change it here first
str_replace("<br />","\n",$myData1); //You also forgot the new line character I think.
$myData1 = strip_tags($myData1);
}
Then you can do this:
<textarea class="ckeditor" name="body1" id="body1">
<?php echo $myData1; ?>
</textarea>
You made a small logic error according to what I see. According to my understanding, you want to strip out the tags but preserve the new line. So change the "< br />" first before you strip out the tags. Hopefully that's what you want I guess.
You are stripping the tags from your file ($myData1 = strip_tags($myData1)). <br /> is a tag, so you're stripping it out too!
This makes your str_replace useless, since the tag has already been stripped. In any case, you shouldn't need that nl2br in the first place, since newline characters are perfectly valid inside text files...
Something very strange happened because according to the user Touch, his method was working on his computer. Unfortunately it wasn't working on mine! So after a while thinking I came to the conclusion that I was over doing some process of replacement of tags. In order to confirm or not this theory of mine I decided do "back-engineer" Touch's method by erasing line by line and seeing what the result was. In the end I saw that my conclusion was correct, I was over doing process of tag replacement because this code:
$text2 = "../conteudos/start/text2.txt";
if (isset($_POST['body2'])) {
$newData = nl2br($_POST['body2']);
$handle = fopen($text2, "w");
fwrite($handle, $newData);
fclose($handle);
}
// ------------------------------------------------
if (file_exists($text2)) {
$myData2 = file_get_contents($text2);
$myData2 = $myData2;
}
worked in perfection. I can only think that this was due to I was using KCEditor...
A big thanks to all that answered, maing me think and helping me this way to achieve my goal!

Read Persian (Unicode chars) text file using php

I am reading one Persian text file (using PHP) with the help of below code:
/* Reading the file name and the book (UTF-8) */
if(file_exists($SourceDirectoryFile))
{
$NameBook = "name.txt";
$AboutBook = "about.txt";
$myFile = "Computer-Technolgy/2 ($i)/".$NameBook;
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
fclose($fh);
echo 'Name file: '. $theData.'<hr/>';
}
name.txt file contents :
آموزش شبكه هاي کامپيوتري (LEARNING NETWORK)
Name file: ����� ���� ��� ��������� (LEARNING NETWORK)
The reason you are seeing this is because you are just echoing the contents raw. Your browser will need more information, in order to display the message in its correct form.
The easiest way is to use the snippet below.
/* Reading the file name and the book (UTF-8) */
if (file_exists($SourceDirectoryFile))
{
$NameBook = "name.txt";
$AboutBook = "about.txt";
// Using file_get_contents instead. Less code
$myFile = "Computer-Technolgy/2 ($i)/" . $NameBook;
$contents = file_get_contents($myFile);
// I want my browser to display UTF-8 characters
header('Content-Type: text/html; charset=UTF-8');
echo 'Name file: ' . $contents . '<hr/>';
}
Please note that the header function needs to be executed at the beginning of the output to the browser. So for instance if you have additional data that is displayed prior to this function, you need to move the header statement at the top. Otherwise you will end up with warnings on screen that the headers have already been set.
You'll need to make sure that the page where you're displaying the text file has correct encoding.
final and best solution is this:
use this line under your connect
mysqli_set_charset( $con, 'utf8');
like this:
$con = mysqli_connect("localhost","root","amirahmad","shoutit");
mysqli_set_charset( $con, 'utf8');
and at the end add this line right under the head tag in your html to make sure your page have utf-8 charset,like this:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
and that's it . you can read formal document here : pph.net charset

Php writing edited script file content cause extra line breaks

In a multilingual site i have two php files that contains php constants.
Like
define('EMAIL', 'Email');
define('GENDER', 'Gender');
.
.
.
I provide editing of these files from admin side using a textarea in form. print full file in textarea.
When ever admin Update the files it contribute redirection issue, means after inclusion of this file header() function fails reporting a non white space character above.
I checked the php file after editing, and it contain a lot of extra space between each php statment as follow,
define('EMAIL', 'Email');
define('GENDER', 'Gender');
define('NAME', 'name');
Also a long single line breaks into many lines like.
define('SENTENCE', 'this is a long sentence that
breaks into many lines according to width of text area as i noted');
So this also contribute error as it must be in single line
I am sure these extra spaces and line breaks are cause of all issues. I am using this code in printing between textarea:
<textarea style="width: 664px; height: 353px;" id="edit_file" name="edit_file"><?php
$file = fopen("../en.php", "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached
while(!feof($file))
{
echo fgets($file);
}
fclose($file);
?> </textarea>
and for saving file:
if(isset($_POST['btn']) && $_SERVER['REQUEST_METHOD']=='POST' && !empty($_POST['btn'])){
if (get_magic_quotes_gpc()) {
$filedata = stripslashes($_POST['edit_file']);
}
$filedata=str_replace(array("<br />'",'\n'),array("",''),$filedata);
$size=strlen($filedata);
$file = fopen("../en.php", "w") or exit("Unable to open file!");
fwrite($file,"$filedata",$size);
fclose($file);
}
There is 1 unexpected quote and \n cannot be put inside simple quotes :
$filedata=str_replace(array("<br />'",'\n'),array("",''),$filedata);
Replace by :
$filedata=str_replace(array("<br />","\n"),array("",''),$filedata);

Categories