简体   繁体   English

用 PHP 从 SFTP 服务器打开 CSV 文件

[英]Opening a CSV file from SFTP server in PHP

We currently open a csv from our server and then do some stuff with the data like this:我们目前从我们的服务器打开一个 csv,然后用这样的数据做一些事情:

$CSVfile = fopen('filename.csv', "r");
if($CSVfile !== FALSE) {
  $count = 0;
  while(! feof($CSVfile)) {
    $data = fgetcsv($CSVfile, 5000, ",");
      if ($count > 0 && !empty($data)) {
        // Do something
      }
   }
}

We need to change the system as the file will now be hosted on an external server so we need to SFTP into it to retrieve the file.我们需要更改系统,因为文件现在将托管在外部服务器上,因此我们需要 SFTP 到其中以检索文件。 I've installed phpseclib and got the connection working but it just keeps echoing the file contents on the screen.我已经安装了 phpseclib 并使连接正常工作,但它只是不断在屏幕上回显文件内容。 I have it set up like this:我是这样设置的:

include 'vendor/autoload.php';

$sftp = new \phpseclib\Net\SFTP('SERVER');
if (!$sftp->login('USERNAME', 'PASSWORD')) {
  exit('Login Failed');
} else {
  $file = $sftp->fetch('FILE_LOCATION');
}

$CSVfile = fopen($file, "r");
if($CSVfile !== FALSE) {
  $count = 0;
  while(! feof($CSVfile)) {
    $data = fgetcsv($CSVfile, 5000, ",");
    if ($count > 0 && !empty($data)) {
      // Do Something
    }
  }
}

How do I get the new system to read the file contents and do something with it rather than just showing all the file contents?如何让新系统读取文件内容并对其进行处理,而不仅仅是显示所有文件内容?

As @verjas commented already, there's no fetch method in phpseclib.正如@verjas 已经评论过的那样,phpseclib 中没有fetch方法。

If you want to download a file to a string, use SFTP::get :如果要将文件下载为字符串,请使用SFTP::get

$contents = $sftp->get("/remote/path/file.csv");

You can then use str_getcsv to parse the contents.然后您可以使用str_getcsv来解析内容。 According to a contributed note at the function documentation , this should do:根据功能文档中贡献注释,这应该:

$data = str_getcsv($contents, "\n"); // parse the rows
foreach ($data as $line) 
{
    $row_data = str_getcsv($line); // parse the items in rows
}

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

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