- 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”
- file_get_contents
- Parameters
- Return Values
- Errors/Exceptions
- Changelog
- Examples
- Notes
- See Also
- User Contributed Notes 6 notes
- Read all text php
- Read file withfgets() Function
- Ready file with file() Function
- Read file with file_get_contents() and explode() Functions
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.
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»
Read all text php
This tutorial will introduce methods to read text files line by line using PHP.
Read file withfgets() Function
To read text files line by line in PHP, use the fgets() function and a while loop. If there is a line, the function returns it; if there are no more lines to read, it returns false. Two parameters are required. The following is the syntax.
In this case, $file resembles a file pointer that refers to an opened file. The number of bytes to be read is indicated by the optional $length argument.
Using the while loop and the fgets() method, we can cycle through each line after using the open() function to read the file. The following text can be found in the text file abc.txt.
Hi
How are you
Have a great day
Create a variable called $txt file and put the fopen() function in it as an example. In r mode, open the file abc.txt. Make a line counter variable called $a and give it the number 1. Make a while loop next. Write the fgets() function with $text file as the parameter inside the loop’s parenthesis. In the loop, give a $line variable the function. Within the body of the loop, print the $line and $a variables together. Increase the $a variable and shut off the file stream using the fclose() method outside of the loop.
Example Code:
$txt_files = fopen('abc.txt','r');
$x = 1;
while ($line = fgets($txt_files)) echo($x." ".$line)."
";
$x++;
>
fclose($txt_files);
?>
1 Hi
2 How are you
3 Have a great day
Ready file with file() Function
The entire file is read into an array by the file() function. The file() method has the following syntax.
file($filename, $flag, $context)
The file path to be read in this case is $filename. Various constants, including FILE USE INCLUDE PATH, FILE IGNORE NEW LINES, and FILE SKIP EMPTY LINES, are included in the optional $flag option. The third one, which defines a context resource, is also optional.
If the file exists or returns false, the file() function returns the entire array. With the help of the foreach() function, we can utilize the function to read the file context line by line. The foreach() function iterates over the whole document, extracting each line one at a time.
Put the filepath, for instance, in the variable $txt file. Create the variable $lines and assign the $txt file parameter to the file() function. Then, go through the file’s contents using the foreach() function. Use $num=>$line as the value and $lines as the iterator. Print the $num and $line variables inside the loop’s body.
Example Code:
$txt_file = 'abc.txt';
$lines = file($txt_file);
foreach ($lines as $num=>$line)echo 'Line '.$num.': '.$line.'
';
>
Line 0: Hi
Line 1: How are you
Line 2: Have a great day
Read file with file_get_contents() and explode() Functions
The entire file is read into a string via the file get contents() function. If the contents are present, it returns the entire file as a string; otherwise, it returns false. The function argument that we can supply is the file path. Using a separator, the explode() function divides a string into an array. The explode() method has the following syntax.
explode(separator, $string, $limit)
When returning the value, the separator option is used to divide the $string into the specified number of $limit pieces. To read a text file line by line in PHP, we can combine the file get contents(), explode(), and foreach() functions.
Create the variable $contents, for instance, and call the file get contents() method on it with the filepath as an input. Use the n character as a separator and $contents as the string when using the explode() method. Give the function to the $lines variable. $lines as $line should be looped using the foreach loop. Print the $line after that inside the loop body.
The $contents variable in the example below returns a string. With the n newline character, we divided it into an array, and then we used the loop to display each line.
Example Code:
$contents=file_get_contents("abc.txt");
$lines=explode("n",$contents);
foreach($lines as $line)echo $line.'
';
>
Hi
How are you
Have a great day
That's it, hope it's helpful.