PHP - How do I cut out a block of lines in a text document?
How do I cut out a chunk of text from a text file in PHP. For instance, I want to take out 开发者_运维问答lines 0-50 and turn it into a string. Maybe even put some html formatting in there. I already know what lines I need to cut out I just dont know how to select them and put them into a string.
Use file($filename). The result is an array where each element is a line from your file. Sample:
$lines = file("foo.txt");
//extract desired lines
$lines = array_slice($lines,19,21);
$string ) implode("\n",$lines);
explode on new line and output the array values from 0-50.
Open the file with fopen, read first 50 lines using fgets.
$fp = fopen('myfile.txt', 'rt');
if ($fp)
{
for ($i = 0; $i < 50; $i++)
{
$s = fgets($fp);
...add error checking and do something with the line here
}
}
This is efficient even if you need to read first 50 lines of a large file.
Less memory intensive approach:
$fileObject = new SplFileObject('yourFile.txt');
$fileIterator = new LimitIterator($fileObject, 0, 49);
$firstFiftyLines = implode(iterator_to_array($fileIterator));
or as an alternative
$fileObject = new SplFileObject('yourFile.txt');
$fileIterator = new LimitIterator($fileObject, 0, 49);
$firstFiftyLines = '';
foreach ($fileIterator as $currentLine) {
$firstFiftyLines .= $currentLine;
}
If you need other lines, change the second and third argument to the LimitIterator. First one is starting offset, second iteration count (in this context lines to read).
Marking answer CW because question (and answer) is a duplicate of Read a file from line X to line Y?
精彩评论