Saturday, 24 October 2020

PHP - Learning File Handling - Reading a Text File (#PHPCoding)(#PHPFunctions)(#Ipumusings)

PHP - Learning File Handling - Reading a Text File

PHP - Learning File Handling - Reading a Text File (#PHPCoding)(#PHPFunctions)(#Ipumusings)

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;
?>


PHP - Learning File Handling - Reading a Text File (#PHPCoding)(#PHPFunctions)(#Ipumusings)


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";
    }
?>


PHP - Learning File Handling - Reading a Text File (#PHPCoding)(#PHPFunctions)(#Ipumusings)

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));
?>


PHP - Learning File Handling - Reading a Text File (#PHPCoding)(#PHPFunctions)(#Ipumusings)



Syntax for file_get_contents( ) is
file_get_contents(path, include_path, context, start, max_length)

where

path
Required parameter. It specifies the path to the file to read.

include_path
It is an optional parameter. If this parameter is ser to '1', it searches for the file in the include_path (in php.ini) also. 

context
It is an optional parameter. You can use NULL to skip. It specifies the context of the file handle. Context is a set of options that can modify the behavior of stream. 

start
It is an optional parameter. It specifies where in the file to start reading. Negative values count from the end of the file.


max_length
It specifies the maximum length of data read. Default is read to EOF (end of file). It is also an optional parameter.


Return Value:
The function returns the string read on success and FALSE on failure.


👉See Also:


No comments:

Post a comment