如何在PHP中分割CSV文件? [英] How can I split a CSV file in PHP?

查看:662
本文介绍了如何在PHP中分割CSV文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大的CSV文件。我想根据其中一个字段中的值将此文件分成单独的文件。

I have a big CSV file. I want to separate this file into separate files based on the value in one of the fields.

这是我做的。使用fgetcsv我将CSV转换为数组,并使用 in_array ,我检查内容,并显示是否包含数组中的字符串。

This is what I have done. Using fgetcsv I convert the CSV into an array, and using in_array, I check the content and display if it contains the string within the array.

我将从另一个文本文件中获取比较字符串,以检查它是否包含在csv中。在这种情况下,我将其指定为测试。

I will be getting the comparison string from another text file iteratively to check whether it is contained in the csv. In this case I have specified it as "Testing".

以下是代码:

if (($handle = fopen("test.csv", "r")) !== FALSE) {
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {

             if(in_array("Testing", $data))
             {
               var_dump($data);
             }
        }

        fclose($handle);
    }

这是工作,但现在我卡住了。如何将 $ data 写入另一个CSV文件?或者有更好的方法来做这个?

This is working, but now I am stuck. How do I write $data into another CSV file? Or is there a better way to do this?

推荐答案

这实际上很简单,如果字符串只是在线,你甚至不需要fgetcsv。只是

It's actually pretty simple and if the string just has to be on the line, you don't even need fgetcsv. Just

$srcFile = new SplFileObject('test.csv');
$destFile = new SplFileObject('new.csv', 'w+');
foreach ($srcFile as $line) {
    if (strpos($line, 'testing') !== FALSE) {
        $destFile->fwrite($line);
    }
}

这将创建两个文件对象。第一个保存源文件的内容。第二个为包含您的搜索字符串的行创建一个新的文件。然后我们只是遍历每一行,并检查搜索字符串是否存在。如果是这样,我们将其写入目标文件。

This will create two file objects. The first one holding the content of your source file. The second one creating an all new file for the lines containing your search string. We then just iterate over each line and check if the search string exists. If so, we write it to destination file.

源文件不会以这种方式触摸。如果你想有一个文件与搜索字符串和一个文件没有,只是创建一个第三个SplFileObject并添加一个else块到if写入行。最后,删除源csv文件。

The source file will not be touched this way. If you want to have one file with the search string and one file without, just create a third SplFileObject and add an else block to the if writing the line to that one then. In the end, delete the source csv file.

这篇关于如何在PHP中分割CSV文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆