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

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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.