我有一些我用 PHP 的 json_encode()
编码的 JSON 数据,它看起来像这样:
I am having some JSON data that I encoded it with PHP's json_encode()
, it looks like this:
{
"site": "site1",
"nbrSicEnt": 85,
}
我想做的是将数据直接作为文件写入FTP服务器.
What I want to do is to write the data directly as a file onto an FTP server.
出于安全原因,我不希望在将文件发送到 FTP 服务器之前先在本地创建文件,我希望它是动态创建的.因此,例如不使用 tmpfile()
.
For security reasons, I don't want the file to be created locally first before sending it to the FTP server, I want it to be created on the fly. So without using tmpfile()
for example.
当我阅读 ftp_put
的 php 文档时:
When I read the php documentations for ftp_put
:
bool ftp_put ( resource $ftp_stream , string $remote_file ,
string $local_file , int $mode [, int $startpos = 0 ] )
在写入远程文件之前,需要创建一个本地文件(string $local_file
).
Ones needs to create a local file (string $local_file
) before writing it to the remote file.
我正在寻找一种直接写入 remote_file 的方法.如何使用 PHP 做到这一点?
I am looking for a way to directly write into the remote_file. How can I do that using PHP?
file_put_contents
是最简单的解决方案:
The file_put_contents
is the easiest solution:
file_put_contents('ftp://username:password@hostname/path/to/file', $contents);
如果它不起作用,可能是因为您没有启用 URL 包装器PHP.
If it does not work, it's probably because you do not have URL wrappers enabled in PHP.
如果您需要更好地控制写入(传输模式、被动模式、偏移量、读取限制等),请使用 ftp_fput
带有 php://temp
(或 php://memory
)流:
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);
(添加错误处理)
或者您可以直接在 FTP 服务器上打开/创建文件.如果文件很大,这特别有用,因为您不会将全部内容保存在内存中.
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.
请参阅使用 PHP 在外部 FTP 服务器上生成 CSV 文件.
这篇关于不使用中间文件将内存数据传输到 FTP 服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!