如何使用 php 从远程服务器上的 zip 文件读取 csv 文件?

How to read csv file from zip file on remote server with php?

我想从远程服务器读取一个 zip 文件。我目前必须遵循以下代码:

    private $sftp;
    public function __construct($username, $password, $serverName)
    {
        $this->sftp = new Net_SFTP($serverName);
        if (!$this->sftp->login($username, $password)) {
            exit('Login Failed');
        }
    }

    public function buildRecords() {
        $sftp = $this->sftp;
        $sftp -> chdir(Constants::QUICKCHECK_OUTPUT_DIRECTORY);
        echo $sftp->pwd(); // show that we're in the 'test' directory
       // print_r($sftp->nlist());
        foreach($sftp->nlist() as $zipFile) {
            $handle = fopen("zip://" . $zipFile,'r');
            while($line = fgetcsv($handle)) {
                print_r($line);
            }
        }
    }

当我运行这段代码并调用这些方法时,我得到了错误

Warning: fopen(zip://test.zip): failed to open stream: operation failed in /var/www/html/update_alerts2.php on line 67

如何修复此错误? (我正在使用 phpseclib 到 sftp)

fopen 不会仅仅因为您之前使用 phpseclib 登录到服务器就可以神奇地访问远程服务器上的文件。

您必须使用 phpseclib 函数来检索文件内容。

不幸的是,phpseclib 不提供通过 lines/chunks 读取远程文件内容的方法。但是因为它是 CSV 文件,所以一次从文件加载到内存可能是可以的。为此你可以使用 SFTP::get,如果你没有指定 $local_file 参数:

$contents = $sftp->get($zipFile);
$lines = explode("\n", $contents);
foreach ($lines as $line)
{
    if (strlen($line) > 0)
    {
        $fields = str_getcsv($line);
        print_r($fields);
    }
}