6.12 Reading a File Line-by-Line
TechniqueBuild up complete lines one at a time until you reach one without a backslash: <?php $is_more =0; while ($buf = @fgets($fp, 1024)) { trim($buf); if (substr($buf, -1) == _\_){ $line .= substr($buf, 0, -1); $is_more = 1; continue; } else { $line = $is_more ? $line . $buf : $buf; $is_more = 0; } //...Work with $line here } ?> CommentsHere is an example of a file that this program would parse: Here is some text \ Next Line after the continuation character What the code does to parse these files is as follows: First, read the file line-by-line in the while loop, and trim all whitespace on either end. If the line has a continuation character at the end, append $buf to $line , set $is_more to true , and move on to the next line in the file. Otherwise, assign the buffer to $line and set $is_more to . Then we process the full line and continue on to the next line. |