[英]Reading specific line of a file in PHP
我正在讀取php中的文件。 我需要閱讀文件的特定行。
我使用以下代碼:
fseek($file_handle,$start);
while (!feof($file_handle))
{
///Get and read the line of the file pointed at.
$line = fgets($file_handle);
$lineArray .= $line."LINE_SEPARATOR";
processLine($lineArray, $linecount, $logger, $xmlReply);
$counter++;
}
fclose($file_handle);
但是我意識到fseek()
接受字節數而不是行號。
PHP是否有其他功能以行號為基礎的指針?
還是我必須每次都從頭開始讀取文件,並擁有一個計數器,直到讀取所需的行號?
我正在尋找一種有效的算法,單步執行500-1000 Kb的文件以到達所需的行似乎效率低下。
$file = new SplFileObject('yourfile.txt');
$file->seek(123); // seek to line 124 (0-based)
這對您有用嗎?
$file = "name-of-my-file.txt";
$lines = file( $file );
echo $lines[67]; // echos line 68 (lines numbers start at 0 (replace 68 with whatever))
您顯然顯然需要在打印之前檢查行是否存在。 有什么好處嗎
您可以這樣做:
$lines = file($filename); //file in to an array
echo $lines[1]; //line 2
要么
$line = 0;
$fh = fopen($myFile, 'r');
while (($buffer = fgets($fh)) !== FALSE) {
if ($line == 1) {
// $buffer is the second line.
break;
}
$line++;
}
您必須從頭開始閱讀。 但是,如果文件從未/很少更改,則可以將行偏移量緩存在其他位置,也許在另一個文件中。
試試這個,最簡單的一個
$buffer=explode("\n",file_get_contents("filename"));//Split data to array for each "\n"
現在緩沖區是一個數組,每個數組索引包含每一行; 獲得第5行
echo $buffer[4];
您可以使用函數file($filename)
。 此函數將文件中的數據讀取到數組中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.