【问题标题】:PHP Cron Read CSV from URL and Convert to ArrayPHP Cron 从 URL 读取 CSV 并转换为数组
【发布时间】:2021-09-14 20:55:29
【问题描述】:

我正在尝试开发需要每个月发送的电子邮件系统。所以我需要从 php 构建 cron 作业文件。任何人都知道如何从 url 读取文件 CSV 或 Excel 文件,例如:
http://yourdomain.com/cron.php?file=http://google.com/monthly.csv

尝试从 url 读取文件时卡住了。

这是我最近的代码:

<?php

$url = 'http://www1.intranet.com/reportingtool.asp?settings=var&export=ok';
$tmpfname = tempnam(sys_get_temp_dir());
file_put_contents(
    $tmpfname,
    file_get_contents($url)
);
?>

【问题讨论】:

  • 转到手册并阅读 fgetcsv

标签: php csv cron


【解决方案1】:

如果您正在处理远程文件,则应始终牢记这一点

  • 您与遥控器之间的连接可能会中断,您将无法获得完整的文件内容;
  • 文件可能太大而无法即时读取。

在这两种情况下,file_get_contents() 都不是一个很好的使用方法:您应该考虑使用cURL functions。但是,如果上述问题可以忽略不计,您应该可以接受以下问题(正如example here 所建议的那样):

$url = 'http://www1.intranet.com/reportingtool.asp?settings=var&export=ok';
$tmpfname = tempnam(sys_get_temp_dir());
file_put_contents(
    $tmpfname,
    file_get_contents($url)
);
if (($handle = fopen($tmpfname, "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        // Do something with $data, which comes in
        // as an array of values from the current CSV line.
    }
}

【讨论】:

    【解决方案2】:

    有人还需要一个例子,所以把它放在这里: $dataSource 可以是驱动器上的任何文件,也可以是用于解析 csv 的在线链接。

    private array $data = [];
        private string $dataSource = "https://any.csv";
        
    
        if (($open = fopen($dataSource, 'rb')) !== false)
        {
            while (($data = fgetcsv($open, 1000, ";")) !== false)
            {
                $data[] = $data;
            }
            fclose($open);
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-07
      • 1970-01-01
      • 2013-01-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多