如何用 php 读取一个很大的 excel 文件。

本文介绍了一种使用PHP处理大型CSV文件的方法。通过将Excel转换为CSV格式,并利用迭代器逐行读取数据,该程序能够高效地处理每个单元格的值,执行必要的操作并打印结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这个程序是用php 读取一个很大的excel文件,

先将 excel 文件保存成csv 文件,

然后利用 迭代器 逐行读取 excel 单元格的值,

拿到值以后 做相应处理,并打印结果。

 

 

<?php

// 加载 GuzzleHttp 为发送 http 请求提供方便
include_once('./vendor/autoload.php');
$client = new \GuzzleHttp\Client();


    // 定义读取文件
    $file = './file/a.csv';

    function getRows($file)
    {
        $handle = fopen($file, 'rb');


        if (!$handle) {
            throw new Exception();
        }
        while (!feof($handle)) {
             yield fgetcsv($handle);
        }
        fclose($handle);
    }


    // 获取迭代器
    $xrange = getRows($file);
    $ii = 0;

    // 迭代处理 cvs 文件中的每一行内容
    foreach ($xrange as $key => $value) {
        $value = eval('return '.iconv('gbk','utf-8',var_export($value,true)).';');

        $str = $value[4];
        $url = 'http://xxxx.xxxx.com/?api='.$str;

        $response = $client->get($url);
        $body = $response->getBody();
        $remainingBytes = $body->getContents();

        $remainingBytes = json_decode($remainingBytes,true);
        if( !empty($remainingBytes['data']) ){
            $res_ids = '';
            foreach ($remainingBytes['data'] as $kt => $vt) {
                $res_ids .= $vt['outid'].',';
            }
            $res_ids = trim($res_ids,',');
        }else{
            $res_ids = 'error';
        }

            print_r($str);
            echo "\n";
            echo "\n";
            echo "\n";
            print_r($value[4]);
            echo "\n";
            echo "\n";
            echo "\n";
            print_r($res_ids);

        $file = fopen('./new_end/new_a.xls', 'a');
        fwrite($file, $res_ids."\t".$str."\t".$value[4]."\t\n");
        // fclose($file);
        echo "\n";
        echo "\n";
        echo "\n";
        // die;
        $ii++;
        echo "time_________".$ii;
        echo "\n";
        echo "\n";
        echo "\n";
    }

 ?>

转载于:https://www.cnblogs.com/handongyu/p/7676801.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值