简体   繁体   English

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

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

I would like to read a zip file from a remote server.我想从远程服务器读取 zip 文件。 I currently have to following code:我目前必须遵循以下代码:

    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);
            }
        }
    }

When I run this code and call these methods I get the error当我运行此代码并调用这些方法时,我收到错误

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

How do I fix this error?如何修复此错误? (I'm using the phpseclib to sftp) (我正在使用 phpseclib 到 sftp)

fopen will not magically be able to access files on a remote server only because you have logged into the server using phpseclib before. fopen不会神奇地访问远程服务器上的文件,因为您之前已经使用 phpseclib 登录到服务器。

You have to use phpseclib functions to retrieve the file contents.您必须使用 phpseclib 函数来检索文件内容。

Unfortunately phpseclib does not offer a way to read remote file contents by lines/chunks.不幸的是,phpseclib 不提供按行/块读取远程文件内容的方法。 But as it is CSV file, it is probably OK to load from file to memory at once.但是由于它是 CSV 文件,因此一次从文件加载到 memory 可能是可以的。 For that you can use SFTP::get , if you do not specify the $local_file argument:为此,您可以使用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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM