PHP:如果数据文本包含“,”,则创建csv文件,数据将被拆分为多个部分并将其放在其他列中?

I got problems in creating a csv file because if my data contains , it will be splitted into parts and put it in other columns that destroys my csv file.

Here is the sample output:

Sample output link

As what you can see the first row in TITLE column should have this data "Acer Aspire AS5250-0639 15.5" Laptop (1.65 GHz AMD Dual-Core Processor E-450, 4 GB RAM, 500 GB Hard Drive, DVD+/-RW Optical Drive, Windows 7 Home Premium 64-bit)" starting in 4 GB RAM it is splitted and put it in other columns because before it it has , and more.

As of now here is my PHP script:

    <?php
include 'database.php';
$db = new database();

$data = $db->exportdatabase();

$out = '';
$out .= 'GSEQ,BRAND,TITLE,SIMAGE,SPRICE,WEIG,DIMENSIONS,ASIN,CATEGORYNAME,MODELNO';
$out .="
";

foreach($data as $items){
    $out .=' '.$items['GSEQ'].', '.$items['BRAND'].', '.$items['TITLE'].', '.$items['SIMAGE'].', '.$items['SPRICE'].', '.$items['WEIG'].', '.$items['DIMENSIONS'].' 
    '.$items['ASIN'].', '.$items['CATEGORYNAME'].', '.$items['MODELNO'].'
    ';
    $out .="
"; 
    //var_dump($items);
}

header('Content-Description: File Transfer');
header("Content-Type: application/csv") ;
header("Content-Disposition: attachment; filename=Data.csv");
header("Expires: 0");
echo $out;
exit;   
?>

How can I possibly fix this issue?

For starters I would stop trying to do something yourself that PHP can do for you. Use fputcsv instead of doing it yourself: http://php.net/manual/en/function.fputcsv.php. This method also deals with escaping your delimiter ( your comma ).

On top of that.. dont use ',' as your csv seperator. You are probably better off using '|' as a seperater, since that character is way less common.

One method is to wrap each field using quotes (")

Another is to replace the troublesome "," with another character using str_replace.