首页 > 解决方案 > 读取 CSV 文件的限制

问题描述

我有一个包含多行的 CSV 文件,我想在 php 中只恢复第 1 列值等于 27 的数据,我该怎么做?

这就是我已经做过的:

<?php

require(dirname(__FILE__) . '/config/config.inc.php');

$fileDir = 'stock.csv';

$fileCsv = file_get_contents($fileDir);

echo $fileCsv;

我的 CSV 文件有 3 列:

| number | ref | stock |
|   19   | 135 |   10  |
|   27   | 656 |   20  |

谢谢你。

标签: php

解决方案


正如 RiggsFolly 指出的那样;fgetscsv() 是您最好的工具。

$fileDir = 'stock.csv';
//open the file for reading
$fileCsv = fopen($fileDir,"r");
//initialize our output array
$outputData = array();
//define the line length required for fgetcsv
$lineLength = 100;
//loop the contents of csv and split by `,`
while($row = fgetcsv($fileCsv,$lineLength,',')){
   //does our first column equal 27?
    if($row[0] == 27){
        //store the full row into our output array
        $outputData[] = $row;
    }
}
//output
print_r($outputData);

推荐阅读