我需要从一个大型 CSV 文件中读取两列。 CSV 有多个列,有时可以具有以下属性:
- ~25,000 行
- 包含空格和空行
- 不均匀(有些列比其他列长)
在上面的示例 CSV 文件中,我只对“买入”和“卖出”列(A 列和 D 列)中的代码感兴趣。
我已经编写了以下代码(警告:它不是很优雅)来遍历所有行并只读取我需要的列。我创建字符串作为 1 个大型 MYSQL 查询的输入(而不是运行许多小型查询)。
<?php
//Increase the allowed execution time
set_time_limit(0);
ini_set('memory_limit','256M');
ini_set('max_execution_time', 0);
//Set to detect the ending of CSV files
ini_set('auto_detect_line_endings', true);
$file = "test.csv";
$buy = $sold = ""; //Initialize empty strings
if (($handle = @fopen($file, "r")) !== FALSE) {
while (($pieces = fgetcsv($handle, 100, ",")) !== FALSE) {
if ( ! empty($pieces[0]) ) {
$buy .= $pieces[0] ." ";
}
if ( ! empty($pieces[3]) ) {
$sold .= $pieces[3] ." ";
}
}
echo "Buy ". $buy ."<br>"; //Do something with strings...
echo "Sold ". $sold ."<br>";
//Close the file
fclose($handle);
}
?>
我的问题是:这是执行此类任务的最佳方式吗?该代码适用于较小的测试文件,但在像这样迭代 CSV 文件时是否有我忽略的缺点?
最佳答案
首先,如果将大文件存储在变量中,读取任何大文件都会消耗内存。您可以查看reading large files(more than 4GB in unix)
其次,你可以输出$buy & $sold 在 while 循环中,这两个变量不保存在内存中的方式可能会提高内存效率。
最后,在php中使用文件查找方法fseek documentation
关于php - 从 PHP 中的大型 CSV 文件中读取多列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20728428/