2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > php读取文件行读 如何在php中按行读取文件

php读取文件行读 如何在php中按行读取文件

时间:2020-06-15 23:17:13

相关推荐

php读取文件行读 如何在php中按行读取文件

您可以使用fgets()函数逐行读取文件:

$handle = fopen("inputfile.txt", "r"); if ($handle) { while (($line = fgets($handle)) !== false) { // process the line read. } fclose($handle); } else { // error opening the file. }

if ($file = fopen("file.txt", "r")) { while(!feof($file)) { $line = fgets($file); # do same stuff with the $line } fclose($file); }

<?php $file = new SplFileObject("file.txt"); // Loop until we reach the end of the file. while (!$file->eof()) { // Echo one line from the file. echo $file->fgets(); } // Unset the file to call __destruct(), closing the file handle. $file = null;

使用缓冲技术来读取文件。

$filename = "test.txt"; $source_file = fopen( $filename, "r" ) or die("Couldn't open $filename"); while (!feof($source_file)) { $buffer = fread($source_file, 4096); // use a buffer of 4KB $buffer = str_replace($old,$new,$buffer); /// }

有一个file()函数返回文件中包含的行的数组。

foreach(file('myfile.txt') as $line) { echo $line. "\n"; }

foreach (new SplFileObject(__FILE__) as $line) { echo $line; }

如果你打开一个大文件,你可能需要在fgets()旁边使用Generators,以避免将整个文件加载到内存中:

/** * @return Generator */ $fileData = function() { $file = fopen(__DIR__ . '/file.txt', 'r'); if (!$file) die('file does not exist or cannot be opened'); while (($line = fgets($file)) !== false) { yield $line; } fclose($file); };

像这样使用它:

foreach ($fileData() as $line) { // $line contains current line }

这样你可以处理foreach()中的单个文件行。

注意:生成器需要> = PHP 5.5

注意'while(!feof … fgets()')的东西,fgets可以得到一个错误(returnfing false)并且永远循环而不会到达文件的末尾。codaddict最接近正确,但是当你的'fgets'循环结束,检查feof;如果不是true,那么你有一个错误。

对这个问题的一个stream行的解决scheme将有新的行字符的问题。 它可以用一个简单的str_replace很容易地修复。

$handle = fopen("some_file.txt", "r"); if ($handle) { while (($line = fgets($handle)) !== false) { $line = str_replace("\n", "", $line); } fclose($handle); }

这是我如何pipe理非常大的文件(testing高达100G)。 它比fgets()更快

$block =1024*1024;//1MB or counld be any higher than HDD block_size*2 if( $fh = fopen("file.txt", "r") ){ $left=''; while (!feof($fh)) {// read the file $temp = fread($fh, $block); $fgetslines = explode("\n",$temp); $lines[0]=$left.$lines[0]; if(!feof($fh) )$left = array_pop($lines); foreach($lines as $k => $line){ //do smth with $line } } } fclose($fh);

函数读取数组返回

function read_file($filename = ''){ $buffer = array(); $source_file = fopen( $filename, "r" ) or die("Couldn't open $filename"); while (!feof($source_file)) { $buffer[] = fread($source_file, 4096); // use a buffer of 4KB } return $buffer; }

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。