6.12 Reading a File Line-by-Line


6.12 Reading a File Line-by-Line

You have a file that has long lines split over two or more lines, with backslashes indicating that a continuation line follows . You want to put those lines back together. Shells, scripts, makefiles, and many other scripting or configuration languages let you use backslashes to break a long line into several shorter ones.

Technique

Build 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 } ?> 

Comments

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



PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net