Recipe 23.10. Processing Variable-Length Text Fields


23.10.1. 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.

23.10.2. Solution

As shown in Example 23-28, read in each line and then split the fields based on their delimiter.

Processing variable-length text fields

<?php $delim = '|'; $fh = fopen('books.txt','r') or die("can't open: $php_errormsg"); while (! feof($fh)) {     $s = rtrim(fgets($fh));     $fields = explode($delim,$s);     // ... do something with the data ... } fclose($fh) or die("can't close: $php_errormsg"); ?>

23.10.3. 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 as shown in Example 23-29.

Processing a list of books

<?php $fh = fopen('books.txt','r') or die("can't open: $php_errormsg"); while (! feof($fh)) {     $s = rtrim(fgets($fh));     list($title,$author,$publication_year) = explode('|',$s);     // ... do something with the data ... } fclose($fh) or die("can't close: $php_errormsg"); ?>

If you supply a line-length argument to fgets( ), it 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.

23.10.4. See Also

Recipe 1.14 discusses ways to break strings into pieces; Recipes Recipe 1.11 and 1.11 cover parsing comma-separated and fixed-width data; documentation on explode( ) at http://www.php.net/explode and rtrim( ) at http://www.php.net/rtrim.




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