douyouming9180 2013-01-24 09:22
浏览 129
已采纳

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?

  • 写回答

2条回答 默认 最新

  • drsxzut183207938 2013-01-24 09:28
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像