Jump to content

read only 1st line of a text document


php_joe

Recommended Posts

is there a way to read a text document into an array, like with the file() function, but have it stop reading the file after just one or two lines?

 

Example: If I wanted to read just the first line of the following text?

 

Text:

Header1, Header2, Header3

Dog, Big, Loyal

Cat, Medium, Aloof

Mouse, Small, Scavenger

 

I know that fread can be stopped after a specified number by bytes has been read. is there a way to have it read until it hits a "\n"?

Link to comment
https://forums.phpfreaks.com/topic/71269-read-only-1st-line-of-a-text-document/
Share on other sites

You can't do that with the file() function, neither can I think of one that you can - Although not a perfect solution, could you set the maxlen parameter of the file_get_contents() function? Or would that be too vague?

 

That's what I'll probably end up doing, I was just hoping for something a little cleaner. ;)

Can't you just use file, set the variables you want and then unset the handler? Eg:

$file = file('myfile.txt');

// set the variables for the first two lines.
$line1 = $file[0];
$line2 = $file[1];

// remove handler.
unset($file).

Exactly!

 

I've got a rather large file full of information. The first page that you see has a search form on it that allows the viewer to search for information within each column, and it uses the first line of the document for the search topics. At the moment I'm using file() and then just $line[0] to get the info but I'd like to have the page load faster if it's possible so I was looking for a way to avoid loading the entire document when it's not needed.

<?php
$lines = file('http://www.yoursite.com');
foreach ($lines as $line_num => $line) {
echo str_replace("","     ",htmlentities($line)) . "<br />\n";
}
?>

 

I used this to get all lines of a file, and in this case it was a html file. If you adjust the looping I'm sure you can print just the first line.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.