note 94954 deleted from function.fgetcsv by danbrown

From: Date: Fri, 04 Dec 2009 14:56:05 +0000
Subject: note 94954 deleted from function.fgetcsv by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-163572@lists.php.net to get a copy of this message
Note Submitter: jaimthorn at yahoo dot com ---- I used fgetcsv to read pipe-delimited data files, and ran into the following quirk. The data file contained data similar to this: RECNUM|TEXT|COMMENT 1|hi!|some comment 2|"error!|another comment 3|where does this go?|yet another comment 4|the end!"|last comment I read the file like this: <?php $row = fgetcsv( $fi, $length, '|' ); ?> This causes a problem on record 2: the quote immediately after the pipe causes the file to be read up to the following quote --in this case, in record 4. Everything in between was stored in a single element of $row. In this particular case it is easy to spot, but my script was processing thousands of records and it took me some time to figure out what went wrong. The annoying thing is, that there doesn't seem to be an elegant fix. You can't tell PHP not to use an enclosure --for example, like this: <?php $row = fgetcsv( $fi, $length, '|', '' ); ?> (Well, you can tell PHP that, but it doesn't work.) So you'd have to resort to a solution where you use an extremely unlikely enclosure --for example, like this: <?php $row = fgetcsv( $fi, $length, '|', '0b80be9265be2e277665d9667acfcf03' ); ?> In this example, I chose the self-explanatory (?) md5( 'this is an extremely unlikely enclosure' ) as an extremely unlikely enclosure... Alternatively (and IMNSHO: more elegantly), you can choose to read these files like this, instead: <?php $line = fgets( $fi, $length ); $row = explode( '|', $line ); ?> As it's more intuitive and resilient, I've decided to favor this 'construct' over fgetcsv from now on.

« previous php.notes (#163572) next »