working with a csv with odd encapsulation // php
Posted
by Patrick
on Stack Overflow
See other posts from Stack Overflow
or by Patrick
Published on 2010-04-10T08:00:24Z
Indexed on
2010/04/10
8:03 UTC
Read the original article
Hit count: 211
I have a CSV file that im working with, and all the fields are comma separated. But some of the fields themselves, contain commas. In the raw csv file, the fields that contain commas, are encapsulated with quotes, as seen here;
"Doctor Such and Such, Medical Center","555 Scruff McGruff, Suite 103, Chicago IL 60652",(555) 555-5555,,,,something else
the code im using is below
<?PHP
$file_handle = fopen("file.csv", "r");
$i=0;
while (!feof($file_handle) ) {
$line = fgetcsv($file_handle, 1024);
$c=0;
foreach($line AS $key=>$value){
if($i != 0){
if($c == 0){
echo "[ROW $i][COL $c] - $value"; //First field in row, show row #
}else{
echo "[COL $c] - $value"; // Remaining fields in row
}
}
$c++;
}
echo "<br>"; // Line Break to next line
$i++;
}
fclose($file_handle);
?>
The problem is im getting the fields with the comma's split into two fields, which messes up the number of columns im supposed to have.
Is there any way i could search for comma's within quotes and convert them, or another way to deal with this?
© Stack Overflow or respective owner