Create CSV File in PHP and Save to SFTP using phpseclib

283

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

Answer

Solution:

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.

516

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.

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

People are also looking for solutions to the problem: php - Simple Dom Parser or CURL TABLE PARSING

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.