php - 从 PHP 中的大型 CSV 文件中读取多列

标签 php csv

我需要从一个大型 CSV 文件中读取两列。 CSV 有多个列,有时可以具有以下属性:

  1. ~25,000 行
  2. 包含空格和空行
  3. 不均匀(有些列比其他列长)

enter image description here

在上面的示例 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/

相关文章:

php - 使用 PHP 连接到特定的 DB2 模式

javascript - 在 JavaScript 中成功验证后我无法显示任何消息

python - 使用 python 将 CSV 文件转换为 JSON 文件

mysql - 选择具有逗号分隔值的列包含 ID 的位置

xml - 实现PowerShell XML to CSV解决方案的问题

php - OpenID登录后获取数据

php - Apache 的可暂停下载

javascript - 最后在 tbody 的每个表行中插入额外的列

ruby-on-rails - Rails 导出到 CSV 文件

python 错误;统一码编码错误 : 'ascii' codec can't encode character u'\u2026'