November 2002
Intermediate to advanced
640 pages
16h 33m
English
You need to break apart fixed-width records in strings.
Use substr( )
:
$fp = fopen('fixed-width-records.txt','r') or die ("can't open file");
while ($s = fgets($fp,1024)) {
$fields[1] = substr($s,0,10); // first field: first 10 characters of the line
$fields[2] = substr($s,10,5); // second field: next 5 characters of the line
$fields[3] = substr($s,15,12); // third field: next 12 characters of the line
// a function to do something with the fields
process_fields($fields);
}
fclose($fp) or die("can't close file");Or unpack( )
:
$fp = fopen('fixed-width-records.txt','r') or die ("can't open file");
while ($s = fgets($fp,1024)) {
// an associative array with keys "title", "author", and "publication_year"
$fields = unpack('A25title/A14author/A4publication_year',$s);
// a function to do something with the fields
process_fields($fields);
}
fclose($fp) or die("can't close file");Data 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 ...