- Fetching Text Data From a Text File Using PHP
- Read or fetch data from a text file in PHP
- PHP Program To Fetch Text File Texts
- PHP program to store user input from an HTML file in a text file and Retrieve that text at the same time
- 12 responses to “Fetching Text Data From a Text File Using PHP”
- PHP File Open/Read/Close
- PHP Open File — fopen()
- Example
- PHP Read File — fread()
- PHP Close File — fclose()
- PHP Read Single Line — fgets()
- Example
- PHP Check End-Of-File — feof()
- Example
- PHP Read Single Character — fgetc()
- Example
- Complete PHP Filesystem Reference
- file_get_contents
- Parameters
- Return Values
- Errors/Exceptions
- Changelog
- Examples
- Notes
- See Also
- User Contributed Notes 6 notes
Fetching Text Data From a Text File Using PHP
Sometimes its become very essential to get text file data and showing that in a browser or we have to store the data in our database. But whatever you do with that retrieved data in PHP, at first you need to know how to retrieve that text data easily in PHP.
Read or fetch data from a text file in PHP
So today I am again here to provide the easiest way ever to retrieve the text from a text file (.txt file) in PHP.
I assume that you have a text file with having some text in it and I am gonna show you what to do in order to retrieve that text data using PHP.
For those curious learners who want to know how to insert text data into a text file using PHP may click the below link
From there you can learn those things.
PHP Program To Fetch Text File Texts
In PHP there is a function file_get_contents()
This function will be very fruitful to us as this PHP function reads a file into a string.
this small piece of code is enough to display your Text data. ( data.txt is the file name of a text file, you can replace it with your file name.
Now suppose you want to store the text string you have fetched in a variable then you can use the below code.
But remember you can directly put the file name if your PHP file and text file resides in the same directory or folder. Otherwise, you have to mention the file name followed by the path.
PHP program to store user input from an HTML file in a text file and Retrieve that text at the same time
The below PHP program will help you to store user input text by HTML form in a text file and when the user click on the submit button the page will show you the text retrieving the text from the text file.
Enter Your Text Here:
?>
If you have any query regarding this content may comment in the below comment section area.
12 responses to “Fetching Text Data From a Text File Using PHP”
I copy/pasted the code as it is and opened it in firefox as well as safari. In both, after entering text and click submit button, the data.txt file is still empty. Any idea why the data is not stored in data.txt file?
The code has been tested on Chrome and its working. Please check your code and server settings. If the problem still not resolved send your code.
hi, i have copied the code and pasted and opened in chrome but the file isn’t saved.please help its urgent.
PHP File Open/Read/Close
In this chapter we will teach you how to open, read, and close a file on the server.
PHP Open File — fopen()
A better method to open files is with the fopen() function. This function gives you more options than the readfile() function.
We will use the text file, «webdictionary.txt», during the lessons:
AJAX = Asynchronous JavaScript and XML
CSS = Cascading Style Sheets
HTML = Hyper Text Markup Language
PHP = PHP Hypertext Preprocessor
SQL = Structured Query Language
SVG = Scalable Vector Graphics
XML = EXtensible Markup Language
The first parameter of fopen() contains the name of the file to be opened and the second parameter specifies in which mode the file should be opened. The following example also generates a message if the fopen() function is unable to open the specified file:
Example
$myfile = fopen(«webdictionary.txt», «r») or die(«Unable to open file!»);
echo fread($myfile,filesize(«webdictionary.txt»));
fclose($myfile);
?>?php
Tip: The fread() and the fclose() functions will be explained below.
The file may be opened in one of the following modes:
Modes | Description |
---|---|
r | Open a file for read only. File pointer starts at the beginning of the file |
w | Open a file for write only. Erases the contents of the file or creates a new file if it doesn’t exist. File pointer starts at the beginning of the file |
a | Open a file for write only. The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn’t exist |
x | Creates a new file for write only. Returns FALSE and an error if file already exists |
r+ | Open a file for read/write. File pointer starts at the beginning of the file |
w+ | Open a file for read/write. Erases the contents of the file or creates a new file if it doesn’t exist. File pointer starts at the beginning of the file |
a+ | Open a file for read/write. The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn’t exist |
x+ | Creates a new file for read/write. Returns FALSE and an error if file already exists |
PHP Read File — fread()
The fread() function reads from an open file.
The first parameter of fread() contains the name of the file to read from and the second parameter specifies the maximum number of bytes to read.
The following PHP code reads the «webdictionary.txt» file to the end:
PHP Close File — fclose()
The fclose() function is used to close an open file.
It’s a good programming practice to close all files after you have finished with them. You don’t want an open file running around on your server taking up resources!
The fclose() requires the name of the file (or a variable that holds the filename) we want to close:
PHP Read Single Line — fgets()
The fgets() function is used to read a single line from a file.
The example below outputs the first line of the «webdictionary.txt» file:
Example
$myfile = fopen(«webdictionary.txt», «r») or die(«Unable to open file!»);
echo fgets($myfile);
fclose($myfile);
?>?php
Note: After a call to the fgets() function, the file pointer has moved to the next line.
PHP Check End-Of-File — feof()
The feof() function checks if the «end-of-file» (EOF) has been reached.
The feof() function is useful for looping through data of unknown length.
The example below reads the «webdictionary.txt» file line by line, until end-of-file is reached:
Example
$myfile = fopen(«webdictionary.txt», «r») or die(«Unable to open file!»);
// Output one line until end-of-file
while(!feof($myfile)) echo fgets($myfile) . «
«;
>
fclose($myfile);
?>?php
PHP Read Single Character — fgetc()
The fgetc() function is used to read a single character from a file.
The example below reads the «webdictionary.txt» file character by character, until end-of-file is reached:
Example
$myfile = fopen(«webdictionary.txt», «r») or die(«Unable to open file!»);
// Output one character until end-of-file
while(!feof($myfile)) echo fgetc($myfile);
>
fclose($myfile);
?>?php
Note: After a call to the fgetc() function, the file pointer moves to the next character.
Complete PHP Filesystem Reference
For a complete reference of filesystem functions, go to our complete PHP Filesystem Reference.
file_get_contents
This function is similar to file() , except that file_get_contents() returns the file in a string , starting at the specified offset up to length bytes. On failure, file_get_contents() will return false .
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.
Note:
If you’re opening a URI with special characters, such as spaces, you need to encode the URI with urlencode() .
Parameters
Note:
The FILE_USE_INCLUDE_PATH constant can be used to trigger include path search. This is not possible if strict typing is enabled, since FILE_USE_INCLUDE_PATH is an int . Use true instead.
A valid context resource created with stream_context_create() . If you don’t need to use a custom context, you can skip this parameter by null .
The offset where the reading starts on the original stream. Negative offsets count from the end of the stream.
Seeking ( offset ) is not supported with remote files. Attempting to seek on non-local files may work with small offsets, but this is unpredictable because it works on the buffered stream.
Maximum length of data read. The default is to read until end of file is reached. Note that this parameter is applied to the stream processed by the filters.
Return Values
The function returns the read data or false on failure.
This function may return Boolean false , but may also return a non-Boolean value which evaluates to false . Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.
Errors/Exceptions
An E_WARNING level error is generated if filename cannot be found, length is less than zero, or if seeking to the specified offset in the stream fails.
When file_get_contents() is called on a directory, an E_WARNING level error is generated on Windows, and as of PHP 7.4 on other operating systems as well.
Changelog
Version | Description |
---|---|
8.0.0 | length is nullable now. |
7.1.0 | Support for negative offset s has been added. |
Examples
Example #1 Get and output the source of the homepage of a website
Example #2 Searching within the include_path
// If strict types are enabled i.e. declare(strict_types=1);
$file = file_get_contents ( ‘./people.txt’ , true );
// Otherwise
$file = file_get_contents ( ‘./people.txt’ , FILE_USE_INCLUDE_PATH );
?>?php
Example #3 Reading a section of a file
// Read 14 characters starting from the 21st character
$section = file_get_contents ( ‘./people.txt’ , FALSE , NULL , 20 , 14 );
var_dump ( $section );
?>?php
The above example will output something similar to:
Example #4 Using stream contexts
// Create a stream
$opts = array(
‘http’ =>array(
‘method’ => «GET» ,
‘header’ => «Accept-language: en\r\n» .
«Cookie: foo=bar\r\n»
)
);
?php
$context = stream_context_create ( $opts );
// Open the file using the HTTP headers set above
$file = file_get_contents ( ‘http://www.example.com/’ , false , $context );
?>
Notes
Note: This function is binary-safe.
A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.
When using SSL, Microsoft IIS will violate the protocol by closing the connection without sending a close_notify indicator. PHP will report this as «SSL: Fatal Protocol Error» when you reach the end of the data. To work around this, the value of error_reporting should be lowered to a level that does not include warnings. PHP can detect buggy IIS server software when you open the stream using the https:// wrapper and will suppress the warning. When using fsockopen() to create an ssl:// socket, the developer is responsible for detecting and suppressing this warning.
See Also
- file() — Reads entire file into an array
- fgets() — Gets line from file pointer
- fread() — Binary-safe file read
- readfile() — Outputs a file
- file_put_contents() — Write data to a file
- stream_get_contents() — Reads remainder of a stream into a string
- stream_context_create() — Creates a stream context
- $http_response_header
User Contributed Notes 6 notes
file_get_contents can do a POST, create a context for that first:
$opts = array( ‘http’ =>
array(
‘method’ => ‘POST’ ,
‘header’ => «Content-Type: text/xml\r\n» .
«Authorization: Basic » . base64_encode ( » $https_user : $https_password » ). «\r\n» ,
‘content’ => $body ,
‘timeout’ => 60
)
);
$context = stream_context_create ( $opts );
$url = ‘https://’ . $https_server ;
$result = file_get_contents ( $url , false , $context , — 1 , 40000 );
Note that if an HTTP request fails but still has a response body, the result is still false, Not the response body which may have more details on why the request failed.
There’s barely a mention on this page but the $http_response_header will be populated with the HTTP headers if your file was a link. For example if you’re expecting an image you can do this:
$mimetype = null ;
foreach ( $http_response_header as $v ) if ( preg_match ( ‘/^content\-type:\s*(image\/[^;\s\n\r]+)/i’ , $v , $m )) $mimetype = $m [ 1 ];
>
>
if (! $mimetype ) // not an image
>
if the connection is
content-encoding: gzip
and you need to manually ungzip it, this is apparently the key
$c=gzinflate( substr($c,10,-8) );
(stolen from the net)
//从指定位置获取指定长度的文件内容
function file_start_length($path,$start=0,$length=null) if(!file_exists($path)) return false;
$size=filesize($path);
if($start <0) $start+=$size;
if($length===null) $length=$size-$start;
return file_get_contents($path, false, null, $start, $length );
>
I’m not sure why @jlh was downvoted, but I verified what he reported.
>>> file_get_contents($path false, null, 5, null)
=> «»
>>> file_get_contents($path, false, null, 5, 5)
=> «r/bin»