On Wed, 3 Oct 2001 21:25, Sharat Hegde wrote: > Hello, > > I am trying to parse a CSV (comma separated file) file to get the > separate elements. The format of each line of the file is as follows: > > R001,23,"2,5" > > Note that the 3rd field "2,5" is enclosed within quotes as it has > commas within the field itself. This is a standard file created when an > Excel file is saved as a CSV file. What I need after parsing this is an > array with the elements being: > Element 0 - R001 > Element 1 - 23 > Element 2 - 2,5 > > Standard split command gives 4 elements instead of 3. > > I know I can do this by some brute programming, but is there an elegant > way out. Note that I am not using PHP 4.0 and hence PHP4 specific > features are not available to me as yet! > > Regards, > Sharat
>From the manual - may be what you want: fgetcsv (PHP 3>= 3.0.8, PHP 4 >= 4.0.0) Gets line from file pointer and parse for CSV fields array fgetcsv (int fp, int length, string [delimiter]) Similar to fgets() except that fgetcsv() parses the line it reads for fields in CSV format and returns an array containing the fields read. The field delimiter is a comma, unless you specify another delimiter with the optional third parameter. Fp must be a valid file pointer to a file successfully opened by fopen(), popen(), or fsockopen() Length must be greater than the longest line to be found in the CSV file (allowing for trailing line-end characters). fgetcsv() returns FALSE on error, including end of file. N.B. A blank line in a CSV file will be returned as an array comprising a single NULL field, and will not be treated as an error. Example 1. fgetcsv() example - Read and print entire contents of a CSV file $row = 1; $fp = fopen ("test.csv","r"); while ($data = fgetcsv ($fp, 1000, ",")) { $num = count ($data); print "<p> $num fields in line $row: <br>"; $row++; for ($c=0; $c<$num; $c++) { print $data[$c] . "<br>"; } } fclose ($fp); -- David Robley Techno-JoaT, Web Maintainer, Mail List Admin, etc CENTRE FOR INJURY STUDIES Flinders University, SOUTH AUSTRALIA There is something to be said about me: "Wow!!" -- PHP General Mailing List (http://www.php.net/) To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] To contact the list administrators, e-mail: [EMAIL PROTECTED]