PHP - Learning File Handling - Reading a Text File (#PHPCoding)(#PHPFunctions)(#Ipumusings)
PHP - Learning File Handling - Reading a Text File
PHP 4.3 introduce a function file_get_contents( ) which reads the entire file into a string.
file_get_contents( ) is the preferred way to read the contents of a file into a string. It will use memory mapping techniques if supported by your OS to enhance performance.
Here is a snippet shows how to read and display a text file.
<?php // Read file into a string $str = file_get_contents('test/poem.txt'); echo $str; ?>
The issue is file_get_contents( ) does not respect white spaces. Here, it does not honour newline. It can be sorted out in numerous ways. One way is to use <pre> tag.
<?php // Read file into a string $str = file_get_contents('test/poem.txt'); if (str) { echo "<pre>".$str ."</pre>"; } else { print "Could not open file.\n"; } ?>
Alternately, you can encode read string as HTML text and convert newlines int to <br> tags with nl2br( ) function.
<?php // Read file into a string $str = file_get_contents('./poem.txt'); //echo "<pre>".$str ."</pre>"; print nl2br(htmlentities($str)); ?>