简体   繁体   English

在PHP中创建CSV文件并使用phpseclib保存到SFTP

[英]Create CSV File in PHP and Save to SFTP using phpseclib

I need to generate a CSV file from a MySQL query and save the file to an SFTP server. 我需要从MySQL查询生成CSV文件,然后将文件保存到SFTP服务器。 I have tried the code below. 我尝试了下面的代码。 The CSV file gets created, but it is empty. CSV文件已创建,但为空。 I also receive an error message in the browser that says Warning: is_file() expects parameter 1 to be a valid path, resource given in regard to this line $sftp->put($fileName, $fp, NET_SFTP_LOCAL_FILE); 我还在浏览器中收到一条Warning: is_file() expects parameter 1 to be a valid path, resource given消息, Warning: is_file() expects parameter 1 to be a valid path, resource given为此行提供的Warning: is_file() expects parameter 1 to be a valid path, resource given $sftp->put($fileName, $fp, NET_SFTP_LOCAL_FILE); . If I move fclose($fp); 如果我移动fclose($fp); to the last line, I don't get the error but data still doesn't appear in the file. 到最后一行,我没有收到错误,但是数据仍然没有出现在文件中。 Could someone please let me know how to get the data to save in the file that was created? 有人可以让我知道如何将数据保存到创建的文件中吗?

$fileName = 'dataFiles/reports/Report Summary/Report Summary.csv';
$sql = mysqli_query($db, "
        SELECT *
        FROM   reports
        WHERE reportID = 1
");

$fp = fopen('php://output', 'w');
$first = true;

while($row = mysqli_fetch_assoc($sql)){
    if ($first) {
        fputcsv($fp, array_keys($row));
        $first = false;
    }
    fputcsv($fp, $row);
}
fclose($fp);
$sftp->put($fileName, $fp, NET_SFTP_LOCAL_FILE);

The second argument is not a handle but the content directly. 第二个参数不是句柄,而是直接的内容。

I think you could do: stream_get_contents($fp); 我认为您可以做到: stream_get_contents($fp); in the second argument. 在第二个参数中。

$content = stream_get_contents($fp);
fclose($fp);
$sftp->put($fileName, $content, NET_SFTP_LOCAL_FILE);

Try something like this: 尝试这样的事情:

<?php
$fp = fopen('php://temp', 'r+');
// do stuff
rewind($fp);
$sftp->put($filename, $fp);

phpseclib (assuming you're using a new enough version) will detect that the second parameter is a stream resource and will try to read from it accordingly. phpseclib(假设您使用的是足够新的版本)将检测到第二个参数是流资源,并将尝试从中读取相应的参数。

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

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