1.11. Parsing Fixed-Width Delimited Data1.11.2. Solution
1.11.3. DiscussionData in which each field is allotted a fixed number of characters per line may look like this list of books, titles, and publication dates: $booklist=<<<END Elmer Gantry Sinclair Lewis1927 The Scarlatti InheritanceRobert Ludlum 1971 The Parsifal Mosaic Robert Ludlum 1982 Sophie's Choice William Styron1979 END; In each line, the title occupies the first 25 characters, the author's name the next 14 characters, and the publication year the next 4 characters. Knowing those field widths, it's straightforward to use substr( ) to parse the fields into an array:
Exploding $booklist into an array of lines makes the looping code the same whether it's operating over a string or a series of lines read in from a file. The loop can be made more flexible by specifying the field names and widths in a separate array that can be passed to a parsing function, as shown in the pc_fixed_width_substr( ) function in Example 1-3. Example 1-3. pc_fixed_width_substr( )
The variable $line_pos keeps track of the start of each field, and is advanced by the previous field's width as the code moves through each line. Use rtrim( ) to remove trailing whitespace from each field. You can use unpack( ) as a substitute for substr( ) to extract fields. Instead of specifying the field names and widths as an associative array, create a format string for unpack( ). A fixed-width field extractor using unpack( ) looks like the pc_fixed_width_unpack( ) function shown in Example 1-4. Example 1-4. pc_fixed_width_unpack( )
Because the A format to unpack( ) means "space padded string," there's no need to rtrim( ) off the trailing spaces. Once the fields have been parsed into $book_array by either function, the data can be printed as an HTML table, for example:
Joining data on </td><td> produces a table row that is missing its first <td> and last </td>. We produce a complete table row by printing out <tr><td> before the joined data and </td></tr> after the joined data. Both substr( ) and unpack( ) have equivalent capabilities when the fixed-width fields are strings, but unpack( ) is the better solution when the elements of the fields aren't just strings. 1.11.4. See AlsoFor more information about unpack( ), see Recipe 1.14 and http://www.php.net/unpack; Recipe 4.9 discusses join( ).
Copyright © 2003 O'Reilly & Associates. All rights reserved. |
|