View Full Version : Line-by-line text parsing (how do I skip lines?)

11-16-2007, 12:52 AM
I'm moving part of a program from Java to PHP, and there's some functionality I can't quite figure out how to translate.

I'm looking for a way to parse text files line-by-line, and searching around I've found out how to do that, but I can't figure out how to control the code so that I can skip past certain lines.

For example, my Java code works like this:

while (line != null) {
// handle empty lines and special lines
if (line.equals("")) { // skip empty lines

line = in.readLine();
} else if (line.contains("Stimuli;")) {
// populate the names array based on line following "Stimuli;"
line = in.readLine();
names = line.split("\t");
line = in.readLine();
} else if (line.contains("Stimulitypes;")) {
more stuff...

so when I hit a line containing "Stimuli;" I can skip to the next line, perform an action on it, and then skip to the next line before re-starting my loop.

This is something I haven't been able to find a way to do with PHP, after much searching I figure my best bet is asking people who deal with PHP on a regular basis. Any insight on how to go about this would be a huge help.


11-16-2007, 01:25 AM
One way to do it is to use fgets() (http://php.net/fgets). You can also use file() (http://http://php.net/file) to load the file into an array and then loop over it, or file_get_contents() (http://php.net/file_get_contents) to load the entire file into a string if you prefer.

After you get the line with a pointer or load it into a variable you can use comparison operators (http://php.net/language.operators.comparison), or functions like empty() (http://php.net/empty) etc. to check the values.

11-16-2007, 05:29 PM
I would recommend using fgets, because the other solutions read the entire file at once. Which can consume quite a bit of memory with large files.