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.
Asked
Active
Viewed 1,215 times
3
-
How are your lines delineated? Hard returns? If so you can explode() your string into an array and then just take the first 50 (0-49) 'lines' from the array. – CrowderSoup Dec 13 '10 at 16:35
-
Here's a very similar question, How to get the first 20 lines of a text file: http://stackoverflow.com/questions/4410077/remove-all-lines-except-first-20-using-php/4410128#4410128 – Surreal Dreams Dec 13 '10 at 16:37
-
@Surreal this is a different question when it comes to cutting arbirtrary blocks out of the text – Gordon Dec 13 '10 at 16:47
-
possible duplicate of [Read a file from line X to line Y ?](http://stackoverflow.com/questions/2808583/read-a-file-from-line-x-to-line-y) – Gordon Dec 13 '10 at 16:52
-
@Gordon: Looks like it kind of is, I see. I read 0-50 and remembered "first 20." I'd say it still could apply and be useful, though it's not the exact same question. – Surreal Dreams Dec 14 '10 at 01:35
-
@Surreal but you are right regarding the duplicate. i've linked a more fitting. – Gordon Dec 14 '10 at 07:47
4 Answers
4
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);

Oliver A.
- 2,870
- 2
- 19
- 21
1
explode on new line and output the array values from 0-50.

DampeS8N
- 3,621
- 17
- 20
-
explode is not very efficient when you have large files. Beside the possible speed issue, you need 2x more memory to do it. Better to read in line by line using fgets or use file() function as Oliver A. suggested. – Milan Babuškov Dec 13 '10 at 16:39
1
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.

Milan Babuškov
- 59,775
- 49
- 126
- 179
0
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?