6.15 Parsing a File with Pattern Separators


You need to process files separated by some pattern separator, something like the following:

 First Name -- Last Name -- E-mail --Address -- City -- graphics/ccc.gif State -- Zip -- Date -- Comments 

Technique

Use explode() to split by the pattern separator ( -- in this case) and then use list to capture the returned values:

 <?php while ($line = @fgets ($fp, 1024)) {      list ($firstname,  $lastname,  $email,            $address,    $city,      $state,            $zip,        $date,      $comments) = explode ("--", line);              // ... do some stuff with the variables } ?> 

Comments

This is a pretty simple recipe. Basically, the file is read line-by-line , and each line is subsequently split up into smaller segments (separated by -- ). We then assign these segments to variables via the list statement. If you want to create variables from the values, you can use "variable" variables or "soft" references (as they are known in Perl), which create a variable from the value of another variable:

 <?php while ($line = @fgets ($fp, 1024)) {      list ($firstname,  $lastname,  $email,            $address,    $city,      $state,            $zip,        $date,      $comments) = explode ("--", $line); //if first name is Sterling then this would // assign the value of $email to $Sterling     $$firstname = $email } ?> 

If you are reading fixed-length records, you can use the unpack() function to parse the file faster:

 <?php while ($line = @fgets ($fp, 1024)) {      list ($firstname,  $lastname,  $email,            $address,    $city,      $state,            $zip,        $date,      $comments) =              array_values (unpack ("A20first/A20last/A40email/A10addr/A19city/                                    A2state/A5zip/A7date/A250comments", $line));              # ... do some stuff with the variables } ?> 

For a full discussion of unpack() , refer to recipe 1.1.



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