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.

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

Save HTML Form Data in a (.txt) Text File in PHP

From there you can learn those things.



Get random text by line number from a text file in PHP

 

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.

<?php 
     echo file_get_contents("data.txt");
?>

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.

<?php
     $retrieved_data=file_get_contents("data.txt");
?>

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.

How To Read A Text File Line By Line In PHP?

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.

<!DOCTYPE html>
<html>
<head>
  <title>Store form data in .txt file</title>
</head>
<body>
  <form method="post">
    Enter Your Text Here:<br>
    <input type="text" name="textdata"><br>
    <input type="submit" name="submit"><br>
      </form>

</body>
</html>


<?php
              
if(isset($_POST['textdata']))
{
$data=$_POST['textdata'];

$fp = fopen('data.txt', 'a');
fwrite($fp, $data);
fclose($fp);
echo file_get_contents("data.txt");
?><br>
<?php
}
?>

If you have any query regarding this content may comment in the below comment section area.

Happy coding 🙂

How to Count The Sub String from a .txt file using PHP

 

Leave a Reply

Your email address will not be published. Required fields are marked *