Search code examples
phpcsvzipsftpfopen

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. 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)


Solution

  • fopen will not magically be able to access files on a remote server only because you have logged into the server using phpseclib before.

    You have to use phpseclib functions to retrieve the file contents.

    Unfortunately phpseclib does not offer a way to read remote file contents by lines/chunks. But as it is CSV file, it is probably OK to load from file to memory at once. For that you can use SFTP::get, if you do not specify the $local_file argument:

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