You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改PHP脚本实现反向读取CSV文件?

反向读取CSV文件的PHP脚本修改方案

方案1:小文件场景(一次性读入内存反转)

如果你的CSV文件体积不大,可以先把所有数据行读入数组,跳过表头后反转数组,再遍历输出。这种方法代码简洁,适合数据量小的场景:

<?php
$filePath = "./data/data-esp8266-$idluf-$currentdata.csv";
$f = fopen($filePath, "r");

// 跳过表头行
fgets($f);

$rows = [];
// 读取所有数据行,指定分号为分隔符
while (($line = fgetcsv($f, 0, ';')) !== false) {
    $rows[] = $line;
}
fclose($f);

// 反转数组,实现从最后一行开始读取
$rows = array_reverse($rows);

// 遍历输出表格行
foreach ($rows as $cells) {
    echo "<tr>\n";
    foreach ($cells as $cell) {
        echo "<td><a style='text-decoration:none;color:#fff;' class='tooltip' data-tool=' $cell'>" . htmlspecialchars($cell) . "</a></td>\n";
    }
    echo "</tr>\n";
}
?>

方案2:大文件场景(高效反向读取,避免内存溢出)

如果CSV文件体积较大,一次性读入内存会导致性能问题或内存溢出,建议用文件指针从末尾倒推的方式逐行读取:

<?php
$filePath = "./data/data-esp8266-$idluf-$currentdata.csv";
$f = fopen($filePath, "r");

// 获取文件总大小
$fileSize = filesize($filePath);
$position = $fileSize;
$rows = [];
$line = '';

// 从文件末尾倒推读取内容
while ($position > 0) {
    fseek($f, --$position);
    $char = fgetc($f);
    
    // 遇到换行符时,处理当前行(排除空行)
    if ($char === "\n" && $line !== '') {
        // 还原倒读的行和单元格
        $line = strrev($line);
        $cells = explode(';', $line);
        $cells = array_map('strrev', $cells);
        $rows[] = $cells;
        $line = '';
    } elseif ($char !== "\r") { // 过滤回车符
        $line .= $char;
    }
}

// 处理文件开头的最后一行数据
if ($line !== '') {
    $line = strrev($line);
    $cells = explode(';', $line);
    $cells = array_map('strrev', $cells);
    $rows[] = $cells;
}

fclose($f);

// 移除表头(数组最后一个元素为原文件的表头行)
array_pop($rows);

// 遍历输出反向后的内容
foreach ($rows as $cells) {
    echo "<tr>\n";
    foreach ($cells as $cell) {
        echo "<td><a style='text-decoration:none;color:#fff;' class='tooltip' data-tool=' $cell'>" . htmlspecialchars($cell) . "</a></td>\n";
    }
    echo "</tr>\n";
}
?>

补充说明

  • 原脚本中fgetcsv后用explode(";", $row)的操作可以省去,直接在fgetcsv的第三个参数指定分隔符为';',就能正确解析分号分隔的CSV内容。
  • 方案1适合小文件,代码易维护;方案2针对大文件优化,避免内存占用过高。

内容的提问来源于stack exchange,提问作者djroby19

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 16:45:26