Jump to content

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).

I originally though that, but I think the OP is trying to pull the top line out of a huge file and trying to do it a bit quicker... Wouldn't that load the whole file into an array before unsetting the handler? Only guessing.

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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.