Recipe 1.12. Generating Fixed-Width Field Data Records


1.12.1. Problem

You need to format data records such that each field takes up a set amount of characters.

1.12.2. Solution

Use pack( ) with a format string that specifies a sequence of space-padded strings. Example 1-32 transforms an array of data into fixed-width records.

Generating fixed-width field data records

<?php $books = array( array('Elmer Gantry', 'Sinclair Lewis', 1927),                 array('The Scarlatti Inheritance','Robert Ludlum',1971),                 array('The Parsifal Mosaic','William Styron',1979) ); foreach ($books as $book) {     print pack('A25A15A4', $book[0], $book[1], $book[2]) . "\n"; } ?>

1.12.3. Discussion

The format string A25A14A4 tells pack( ) to transform its subsequent arguments into a 25-character space-padded string, a 14-character space-padded string, and a 4-character space-padded string. For space-padded fields in fixed-width records, pack( ) provides a concise solution.

To pad fields with something other than a space, however, use substr( ) to ensure that the field values aren't too long and str_pad( ) to ensure that the field values aren't too short. Example 1-33 transforms an array of records into fixed-width records with .-padded fields.

Generating fixed-width field data records without pack( )

<?php $books = array( array('Elmer Gantry', 'Sinclair Lewis', 1927),                 array('The Scarlatti Inheritance','Robert Ludlum',1971),                 array('The Parsifal Mosaic','William Styron',1979) ); foreach ($books as $book) {     $title  = str_pad(substr($book[0], 0, 25), 25, '.');     $author = str_pad(substr($book[1], 0, 15), 15, '.');     $year   = str_pad(substr($book[2], 0, 4), 4, '.');     print "$title$author$year\n"; } ?>

1.12.4. See Also

Documentation on pack( ) at http://www.php.net/pack and on str_pad( ) at http://www.php.net/str_pad. Recipe 1.16 discusses pack( ) format strings in more detail.




PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

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