dongtuo0828 2016-08-07 02:34
浏览 391
已采纳

PHP - 将制表符分隔的TXT文件转换为CSV

I'm trying to convert a tab delimited .txt file into a .csv file.

I was able to use fgetcsv() to open the txt file and get the data for each line with the following code:

$handle = fopen("fileurl.com", "r");
$row = 1;
if (($handle = fopen("fileurl.com", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, "\t")) !== FALSE) {
        $num = count($data);
        echo "<p> $num fields in line $row: <br /></p>
";
        $row++;

        for ($c=0; $c < $num; $c++) {
            echo $data[$c] . "<br />
";
        }

        print_r($data);

    }
    fclose($handle);
}

Now i just need to create a csv file from the data array. I've tried using fputcsv(), but haven't had any luck. I've tried something like this, but the csv file it creates isn't correct and only has 1 row:

$fp = fopen('file.csv', 'w');

fputcsv($fp, $data, "\t");

fclose($fp);

An example of how to create a .csv file from the $data array would be great. I've spent a lot of time researching and trying to get this figured out, but haven't been able to get it working.

  • 写回答

3条回答 默认 最新

  • dongyakui8675 2016-08-07 02:52
    关注

    fputcsv() only writes one line at a time. Not the whole file. You you need to loop through $data in order to add all of that data into your CSV file.

    $fp = fopen('file.csv', 'w');
    foreach ($data as $line) {
        fputcsv($fp, $line);
    }
    fclose($fp);
    

    A full example using your code:

    $handle = fopen("fileurl.com", "r");
    $lines = [];
    if (($handle = fopen("fileurl.com", "r")) !== FALSE) {
        while (($data = fgetcsv($handle, 1000, "\t")) !== FALSE) {
            $lines[] = $data;
        }
        fclose($handle);
    }
    $fp = fopen('file.csv', 'w');
    foreach ($lines as $line) {
        fputcsv($fp, $line);
    }
    fclose($fp);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献