将特定的 CSV 行读取到 PHP 中


reading specific row of csv into php

我有一个大的csv文件,其中包含100000个客户详细信息。我想为我的安卓应用程序获取数据。我想从csv文件中读取特定行。就像我想要客户的所有详细信息cust_id 070507

使用此方法在 php 中读取这么多大文件将花费太多时间。

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

我想要一个简单的解决方案。如果这是最简单的方法,那么请告诉我如何读取特定行?

您可以使用

file() 将文件放入数组中,然后您可以定位特定行并将其解析为 CSV

$lines = file('test.csv');
$row = $lines[70507]; // Assuming one header row
$csvdata = str_getcsv($row); // Parse line to CSV
$num = count($data); // Get number of columns
for ($c=0; $c < $num; $c++) { // Loop through columns
        echo $data[$c] . "<br />'n"; // Echo column
}

这是您读取特定行的方式。

$ch = fopen($link_to_file);
$found = '';
/* If your csv file's first row contains Column Description you can use this to remove the first row in the while */
$header_row = fgetcsv($read_file);
/* This will loop through all the rows until it reaches the end */
while(($row = fgetcsv($ch)) !== FALSE) {
    /* $row is an array of columns from that row starting at 0 */
    $first_column = $row[0];
    /* Here you can do your search */
    /* If found $found = $row[1]; */
    /* Now $found will contain the 2nd column value (if found) */
}