note 94954 added to function.fgetcsv
| From: | jaimthorn at yahoo dot com | Date: | Fri, 04 Dec 2009 10:31:49 +0000 |
| Subject: | note 94954 added to function.fgetcsv | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-163564@lists.php.net to get a copy of this message | ||
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.
----
Server IP: 213.249.64.162
Probable Submitter: 77.249.171.118
----
Manual Page -- http://www.php.net/manual/en/function.fgetcsv.php
Edit -- https://master.php.net/note/edit/94954
Del: integrated -- https://master.php.net/note/delete/94954/integrated
Del: useless -- https://master.php.net/note/delete/94954/useless
Del: bad code -- https://master.php.net/note/delete/94954/bad+code
Del: spam -- https://master.php.net/note/delete/94954/spam
Del: non-english -- https://master.php.net/note/delete/94954/non-english
Del: in docs -- https://master.php.net/note/delete/94954/in+docs
Del: other reasons-- https://master.php.net/note/delete/94954
Reject -- https://master.php.net/note/reject/94954
Search -- https://master.php.net/manage/user-notes.php