Working with a CSV file 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/11
7:33 UTC
Read the original article
Hit count: 371
I have a CSV file that I'm 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 I'm 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 I'm getting the fields with the commas split into two fields, which messes up the number of columns I'm supposed to have.
Is there any way I could search for commas within quotes and convert them, or another way to deal with this?
© Stack Overflow or respective owner