6.17 Accessing Fixed-Length Records


You know the length of your records, but they don't have any special specifier . Therefore, you need to read a certain length at a time and assign it.

Technique

Although substr() will work, it is terribly inefficient and time-consuming ; unpack() is a much better bet:

 <?php while ($line = @fgets($fp, 1024)) {     list (, $name, , $email, , $url) =           unpack("A20name/x5/A50email/x5/A30url", $line);     //... manipulate $name, $email and $url } ?> 

Comments

unpack() is an extremely fast and efficient way of parsing fixed-length records. In the script, we read 20 bytes and place it in $name . (Note the extra comma in the list construct; it is there because unpack() returns an associative array and we want only the array's values.) Then we skip five bytes, read 50 more bytes into $email , skip another five bytes, and read 30 bytes into $url .

Although unpack() is a much faster method of access fixed-length records, you can also use substr() to access fixed-length records, like so:

 <? while ($line = @fgets ($fp, 1024)) {     $name = substr ($line,0,20);     $email = substr ($line, 25, 50);     $url = substr ($line, 80, 30);     // ... manipulate $name, $email and $url } ?> 

However, not only is substr() less efficient than unpack() , it is also not nearly as fast for parsing fixed-length records.



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