Create CSV File in PHP and Save to SFTP using phpseclib
I need to generate aCSV
file from aMySQL
query and save the file to anSFTP
server. I have tried the code below. TheCSV
file gets created, but it is empty. I also receive an error message in the browser that saysWarning: 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);
. If I movefclose($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);
Answer
Solution:
Try something like this:
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.
Answer
Solution:
The second argument is not a handle but the content directly.
I think you could do:
stream_get_contents($fp);
in the second argument.