How can a file be read from a specific line in PHP?
To read a file from a specific line in PHP, you can open the file, seek to the desired line, and then start reading from that point onwards. This can be achieved by using a combination of file handling functions like fopen(), fseek(), and fgets().
$filename = 'example.txt';
$line_number = 5;
$handle = fopen($filename, 'r');
if ($handle) {
for ($i = 1; $i < $line_number; $i++) {
fgets($handle);
}
while (($line = fgets($handle)) !== false) {
echo $line; // Output the content from the specified line onwards
}
fclose($handle);
} else {
echo "Error opening the file.";
}
Keywords
Related Questions
- How can the output of the script execution time be optimized for different environments, such as HTML or CLI compatibility?
- How can PHP developers effectively filter and display users with specific attributes, such as image uploads?
- What is the significance of the error message "Name 'List' for class not allowed" in PHP?