Eyes Charming Eyes Charming - 24 days ago 8
PHP Question

explode csv file on delimiter (;) and delimiter(,)?

when I explode csv file on delimiter (;)
the explode successfully in some excel program and failed in others

also when I explode csv file on delimiter (,)
the explode successfully in some excel program and failed in others

How can I do explode in all versions of excel?
How can I know the perfect delimiter to explode?

yes there is code..

if (!function_exists('create_csv')) {
function create_csv($query, &$filename = false, $old_csv = false) {
if(!$filename) $filename = "data_export_".date("Y-m-d").".csv";
$ci = &get_instance();
$ci->load->helper('download');
$ci->load->dbutil();
$delimiter = ";";
$newline = "\r\n";
$csv = "Data:".date("Y-m-d").$newline;
if($old_csv)
$csv .= $old_csv;
else
$csv .= $ci->dbutil->csv_from_result($query, $delimiter, $newline);
$columns = explode($newline, $csv);
$titles = explode($delimiter, $columns[1]);
$new_titles = array();
foreach ($titles as $item) {
array_push($new_titles, lang(trim($item,'"')));
}
$columns[1] = implode($delimiter, $new_titles);
$csv = implode($newline, $columns);
return $csv;
}
}


sometimes I put $delimiter = ";";
and sometims $delimiter = ",";

thanks..

Answer Source

You can use helper function to detect best delimiter like:

public function find_delimiter($csv)
{
    $delimiters = array(',', '.', ';');
    $bestDelimiter = false;
    $count = 0;
    foreach ($delimiters as $delimiter)
        if (substr_count($csv, $delimiter) > $count) {
            $count = substr_count($csv, $delimiter);
            $bestDelimiter = $delimiter;
        }
    return $bestDelimiter;
}