18.12. Processing Variable Length Text Fields
Problem
You want to read delimited text fields from a file. You might, for example, have a database program that prints records one per line, with tabs between each field in the record, and you want to parse this data into an array.
Solution
Read in each line and then split the fields based on their delimiter:
$delim = '|';
$fh = fopen('books.txt','r') or die("can't open: $php_errormsg");
while (! feof($fh)) {
$s = rtrim(fgets($fh,1024));
$fields = explode($delim,$s);
// ... do something with the data ...
}
fclose($fh) or die("can't close: $php_errormsg");Discussion
To parse the following data in books.txt:
Elmer Gantry|Sinclair Lewis|1927 The Scarlatti Inheritance|Robert Ludlum|1971 The Parsifal Mosaic|Robert Ludlum|1982 Sophie's Choice|William Styron|1979
Process each record like this:
$fh = fopen('books.txt','r') or die("can't open: $php_errormsg");
while (! feof($fh)) {
$s = rtrim(fgets($fh,1024));
list($title,$author,$publication_year) = explode('|',$s);
// ... do something with the data ...
}
fclose($fh) or die("can't close: $php_errormsg");The line length argument to fgets( )
needs to be at least as long as the longest record, so that a record
doesn’t get truncated.
Calling rtrim( )
is necessary because fgets( ) includes the
trailing whitespace in the line it reads. Without rtrim( ), each $publication_year would have a
newline at its end.
See Also
Section 1.12 discusses ways to break apart strings into pieces; Section 1.10 and ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access