首页  >  文章  >  后端开发  >  如何在 PHP 中将 .txt 文件从 FTP 服务器读取到变量中?

如何在 PHP 中将 .txt 文件从 FTP 服务器读取到变量中?

Patricia Arquette
Patricia Arquette原创
2024-10-26 04:41:30581浏览

How to Read a .txt File from an FTP Server into a Variable in PHP?

从 FTP 服务器读取 .txt 文件到 PHP 变量

尝试从 FTP 服务器读取 .txt 文件到 PHP 变量中时作为一个变量,PHP 提供了多种函数和方法。

使用 file_get_contents

最简单的方法是使用 file_get_contents 函数:

<code class="php">$contents = file_get_contents('ftp://username:pa‌​ssword@hostname/path/to/file');</code>

但是,如果此方法失败,通常表明 PHP 中未启用 URL 包装器。

使用 ftp_fget

为了更精细地控制文件读取过程,您可以使用带有流句柄的 ftp_fget 函数:

<code class="php">$conn_id = ftp_connect('hostname');

ftp_login($conn_id, 'username', 'password');

ftp_pasv($conn_id, true);

$h = fopen('php://temp', 'r+');

ftp_fget($conn_id, $h, '/path/to/file', FTP_BINARY, 0);

$fstats = fstat($h);
fseek($h, 0);
$contents = fread($h, $fstats['size']);

fclose($h);
ftp_close($conn_id);</code>

请记住在读取过程中对潜在问题进行错误处理。

以上是如何在 PHP 中将 .txt 文件从 FTP 服务器读取到变量中?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn