I am downloading a table from a database using php and saving it as a .csv file. But when one of the columns contains a comma ',' inside the string the script takes the rest of the string (after the comma) to a new column. How can I make the script to ignore that comma?
I have tried putting a '\' next to it or using stripcslashes() but nothing works.
Part of the Code
$rows = mysqli_fetch_assoc($select_table);
if ($rows)
{
getcsv(array_keys($rows));
}
while($rows)
{
getcsv($rows);
$rows = mysqli_fetch_assoc($select_table);
}
// get total number of fields present in the database
function getcsv($no_of_field_names){
$separate = '';
// do the action for all field names as field name
foreach ($no_of_field_names as $field_name)
{
if (preg_match('/\|\
|,|"/', $field_name))
{
$field_name = '' . str_replace(',','!', $field_name) . '';
}
echo str_replace('!',',', $field_name) . $separate . $field_name;
//sepearte with the comma
$separate = ',';
}
//make new row and line
echo "
";
}
?>
EDIT:
If I don't use comma then the csv file won't load properly in excel (column by column, row by row).
Before anyone starts saying why you doing that and that I AM DOING IT FOR PRACTICE.
puting the $field_name in quotes in order to be considered as a string will do the trick!!
if (preg_match('/\|\
|,|"/', $field_name))
{
$field_name = '"'.$field_name.'"';
//field_name = '' . str_replace(',','.', $field_name) . '';
}
Since you are practicing, here are some basic rules for csv (let's assume comma as separator):
123,test,456
When a field contains a separator, that field has to be enclosed in double quotes:
123,"monitor, Samsung","45,8"
In other words, if a field is enclosed in double quotes that does not mean it is a string, only that there is (or could be) a separator inside the field.
When a quoted field also contains quotes, those have to be escaped with another quote:
123,"monitor 24"", Samsung","45,8"
This is important to remember when you do the parsing yourself. (and actually, once you start using double quotes, all fields containing double quotes should also be quoted, even if there is no separator inside)
Multiline fields also have to be in double quotes:
123,"monitor 24"", Samsung","test multiline
field","45,8"
The above is actually 1 row.