How to read file from specific word in php?

How do I read the first n lines of a file in PHP?

  • How do you read the first n lines of a file in PHP where the line lengths are variable and line n has '----------' on it (that is finding line n by pattern matching)? I see how to read the whole thing, but I only want a few lines of many files. (Has to work on Windows and Unix). Thanks.

  • Answer:

    How about http://www.php.net/manual/en/function.fgets.php with an appropriately-long line-length?

pissfactory at Ask.Metafilter.Com Visit the source

Was this solution helpful to you?

Other answers

that's it! thanks!

pissfactory

Is there a special reason you need to only get the first n lines? If you are worried about running into files that are 200 megs or something, I think uncleozzy has the only approach. But typically I'd just grab the whole file.

y6y6y6

Nevermind............

y6y6y6

Yeah, I would assume that once you issue an input command, the operating system takes over. I don't think you have PHP control over the data as it's being read. So you just have to issue a give-me-the-whole thing or a give-me-this-much command. If you want to be able to read in little bits of data, a database might be a better option. It's pretty easy to hook up MYSQL and PHP.

grumblebee

pissfactory, try substr($file, 0, strripos($file, "----------"));

riffola

riffola: You'll want to surround the dashes by \ns. But even that won't help, as apparantly strripos finds the last match instead of the first, and though it wasn't said explicity I'm assuming pissfactory wants the first.

fvw

I don't know PHP, but regexp knows no borders: (.*?)(?:\n|^)-{10}(?:\n|$) That also accounts for the possibility that it occurs on the first or last line (which, being that it seems like a divider, is probably irrelevent). Then count the occurences of \n in the first (only) submatch, plus one. And you can easily specify the number of dashes, too, which is of extremely mild advantage. You can do the same thing as riffola's does according to fvw - make it match the last one - by removing the first question mark.

abcde

$lines = @file($fileName); for ($i = 0; $lines[$i] != '----------'; $i++) echo $lines[$i];

tomorama

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.