JIYIK CN >

Current Location:Home > Learning > PROGRAM > PHP >

Reading text files in PHP

Author:JIYIK Last Updated:2025/04/12 Views:

This article will introduce the method of reading text files line by line in PHP.


fgets()Use the function to read a text file line by line in PHP

We can read a text file line by line in PHP using the whileread_line function with a loop. This function returns a line if there is one and returns false if there are no more lines to read. It takes two parameters. The syntax is as follows.fgets()

fgets($file, $length)

Here, $fileit is similar to a file pointer pointing to a successfully opened file. $lengthoptions, optional, indicates the number of bytes to read.

We can open()read the file using the function and then whileloop fgets()through each line using the loop through function. We have a text file with the following content abc.txt.

Hi
How are you
Have a great day 

For example, create a variable $txt_fileand write the function in it fopen(). rOpen the file in mode abc.txt. Create a line counter variable $aand 1assign the value to it. Then, create a whileloop. Inside the loop's brackets, write the function with $text_fileas a parameter fgets(). Assign the function to the variable inside the loop $line. Print $linethe variable, connecting it with the variable inside the loop body $a. Increment the variable and close the file stream $ausing the function outside the loop .fclose()

Sample code:

<?php
$txt_file = fopen('abc.txt','r');
$a = 1;
while ($line = fgets($txt_file)) {
 echo($a." ".$line)."<br>";
 $a++;
}
fclose($txt_file);
?>

Output:

1 Hi 
2 How are you 
3 Have a great day

file()Use the function to read a text file line by line in PHP

file()The function reads the entire file into an array. file()The syntax of the function is as follows.

file($filename, $flag, $context)

Here, $filenameis the file path to read. $flagoptions is optional and consists of various constants such as FILE_USE_INCLUDE_PATH, , FILE_IGNORE_NEW_LINESand FILE_SKIP_EMPTY_LINES. The third is also optional and defines a context resource.

file()The function returns the entire array if it exists or returns false. We can use this function foreach()to read the file line by line using the helo context of the function. foreach()The function will go through the entire content and extract each line individually.

For example, store the file path in a variable $txt_file. Write a variable $linesand store the function on it using $txt_fileas the argument . Next, use the function to loop through the contents of the file using as the iterator and as the value. Within the loop body, print the and variables.file()foreach()$lines$num=>$line$num$line

Sample code:

$txt_file = 'abc.txt';

$lines = file($txt_file);
foreach ($lines as $num=>$line)
{
 echo 'Line '.$num.': '.$line.'<br/>';
}

Output:

Line 0: Hi 
Line 1: How are you 
Line 2: Have a great day

Read a file line by line in PHP using the file_get_contents()and functionsexplode()

file_get_contents()The function reads the entire file into a string. If the content exists, it returns the entire file as a string, otherwise it returns false. We can specify the file path as a parameter to the function. explode()The function splits the string into an array using a delimiter. explode()The syntax of the function is as follows.

explode(separator, $string, $limit)

separator$stringThe option is used to separate the from the number of elements in the return value $limit. We can combine the file_get_contents(), explode(), and foreach()functions to read a text file line by line in PHP.

For example, create a variable $contentsand write the function on it using the file path in the argument file_get_contents(). Use explode()the function with \nthe character as a delimiter, $contentsas a string. Assign the function to the variable $lines. Use foreachthe loop to $linesloop over $line. Then, print inside the loop body $line.

In the following example, $contentsthe variable returns the string. We \nsplit it by newline character into an array and print each line using a loop.

Sample code:

$contents=file_get_contents("abc.txt");
$lines=explode("\n",$contents);
foreach($lines as $line){
 echo $line.'<br>';

}

Output:

Hi 
How are you 
Have a great day

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Check if a Post exists in PHP

Publish Date:2025/04/13 Views:170 Category:PHP

PHP $_POST is a super global variable that can contain key-value pairs of HTML form data submitted through the post method. We will learn different ways to check $_POST if a and contains some data in this article. These methods will use iss

PHP with Ajax

Publish Date:2025/04/13 Views:139 Category:PHP

We will use PHP and ajax by printing a simple sum of two numbers 2 and . Also, print a php array in JSON. 3 object We will also use PHP with ajax by getting the HTML formatted output from the number division in PHP. Printing simple addition

Store Div Id in PHP variable and pass it to JavaScript

Publish Date:2025/04/13 Views:51 Category:PHP

This article shows you how to div id store a in a PHP variable and pass it to JavaScript code. We will answer the following questions. What is div id ? How to div id store in a PHP variable? How to pass variables to JavaScript code? Let’s

Returns the article tag with ID from the action page

Publish Date:2025/04/13 Views:80 Category:PHP

Let's say you're in a login form and you enter the wrong information; in this case, you probably want to go back to the login page. PHP has a built-in function header() to redirect a page to a specific page. But what if the login page is at

Switching PHP versions on Ubuntu

Publish Date:2025/04/13 Views:78 Category:PHP

Different tasks may require running multiple versions of PHP. You may need to switch PHP versions by running two sites on the same server or testing older versions of code using outdated methods. We can switch PHP versions on Ubuntu using t

Resizing images in PHP

Publish Date:2025/04/13 Views:155 Category:PHP

In this tutorial article, we will discuss about resizing images in PHP. Load the image before resizing Before we can resize an image, we must first load it as an image resource in our script. This is file_get_contents() different from using

PHP upload image

Publish Date:2025/04/13 Views:61 Category:PHP

We can upload images in PHP using simple file upload operation, but first, php.ini file upload should be enabled from Files. This tutorial demonstrates how to upload images in PHP. php.ini Enable file upload from file in PHP to upload image

Creating a signature from Hash_hmac() and Sha256 in PHP

Publish Date:2025/04/13 Views:107 Category:PHP

PHP has one of the best encryption functions for data security. Hash_hmac() The encrypt function is one of the most famous encryptors. We'll show you how to use hash_hmac and sha256 encryptors to create 安全签名 one that you can store i

Updating PHP 7.x to 7.4 on CentOS

Publish Date:2025/04/13 Views:131 Category:PHP

This article shows the steps to update the PHP version from 7.x version to 7.4 in CentOS. How to Update PHP from 7.X to 7.4 in CentOS Update operating system packages. yum update -y Check your PHP version in CentOS. php -v Prints a list of

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial