Transfer in-memory data to FTP server without using intermediate file

后端 未结 2 521
天涯浪人
天涯浪人 2020-11-27 21:15

I am having some JSON data that I encoded it with PHP\'s json_encode(), it looks like this:

{
    \"site\": \"site1\",
    \"nbrSicEnt\": 85,
}
         


        
2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-27 21:54

    The file_put_contents is the easiest solution:

    file_put_contents('ftp://username:pa‌​ssword@hostname/path/to/file', $contents);
    

    If it does not work, it's probably because you do not have URL wrappers enabled in PHP.


    If you need greater control over the writing (transfer mode, passive mode, offset, reading limit, etc), use the ftp_fput with a handle to the php://temp (or the php://memory) stream:

    $conn_id = ftp_connect('hostname');
    
    ftp_login($conn_id, 'username', 'password');
    ftp_pasv($conn_id, true);
    
    $h = fopen('php://temp', 'r+');
    fwrite($h, $contents);
    rewind($h);
    
    ftp_fput($conn_id, '/path/to/file', $h, FTP_BINARY, 0);
    
    fclose($h);
    ftp_close($conn_id);
    

    (add error handling)


    Or you can open/create the file directly on the FTP server. That's particularly useful, if the file is large, as you won't have keep whole contents in memory.

    See Generate CSV file on an external FTP server in PHP.

提交回复
热议问题