Site icon LinuxCommands.site

php read files by line: use fopen, fgets and feof / or file_get_contents

Sometimes we receive some temporary tasks, such as getting data information based on id.

Usually in this case, the demand side will provide an id list file.

At this time we need to read the file contents by line and query the data according to the id.

Here’s how to use the php fopen, fgets and feof function to read the id by line.

vim readFile.php

<?php

	$file_name = "id_list.txt";
	$fp = fopen($file_name, 'r');
	
	while (!feof($fp)) {
		$buffer = fgets($fp);
		echo $buffer;
	}
	fclose($fp);
➜  php readFile.php

For some small files, you can also read all the contents of the file at once, and then cut by the regular line “\n”.

This method can also achieve the same effect, the following code:

This method can also achieve the same effect, the following code, using the php file_get_contents function.

vim readFile.php

<?php
	$file_name = "id_list.txt";

	$file_content = file_get_contents($file_name);
	$arr = explode("\n", $file_content);
	foreach ($arr as $key => $value) {
		if(!empty($value)) {
			echo $value;
			echo "\n";
		}
	}
➜ php readFile.php

Exit mobile version