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

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

本文介绍了PHP-将制表符分隔的TXT文件转换为CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将制表符分隔的.txt文件转换为.csv文件.

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

我能够使用fgetcsv()打开txt文件,并使用以下代码获取每一行的数据:

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>\n";
        $row++;

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

        print_r($data);

    }
    fclose($handle);
}

现在我只需要从数据数组创建一个csv文件.我试过使用fputcsv(),但没有任何运气.我已经尝试过类似的操作,但是它创建的csv文件不正确,只有1行:

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);

如何从$ data数组创建.csv文件的示例很好.我花了很多时间研究并试图弄清楚这个问题,但一直没能奏效.

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.

推荐答案

fputcsv()一次只写一行.不是整个文件.您需要遍历$data以便将所有数据添加到CSV文件中.

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);

这篇关于PHP-将制表符分隔的TXT文件转换为CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 09:47