使用一个连接读取FTP目录中每个文件的内容


Read contents of every file in FTP directory using one connection

我的目标是连接到FTP帐户,读取特定文件夹中的文件,获取内容并在屏幕上列出。

这就是我所拥有的:

// set up basic connection
$conn_id = ftp_connect('HOST_ADDRESS');
// login with username and password
$login_result = ftp_login($conn_id, 'USERNAME', 'PASSWORD');
if (!$login_result)
{
    exit();
}
// get contents of the current directory
$contents = ftp_nlist($conn_id, "DirectoryName");
$files = [];
foreach ($contents AS $content)
{
    $ignoreArray = ['.','..'];
    if ( ! in_array( $content , $ignoreArray) )
    {
        $files[] = $content;
    }
}

以上操作可以很好地获取我需要获取的内容的文件名。接下来,我想遍历文件名数组,并将内容存储到一个变量中以供进一步处理。

我不知道该怎么做,我想它需要这样的东西:

foreach ($files AS $file )
{
    $handle = fopen($filename, "r");
    $contents = fread($conn_id, filesize($file));
    $content[$file] = $contents;
}

以上想法来自这里:
PHP:如何将.txt文件从FTP服务器读取到变量中?

虽然我不喜欢每次都必须连接才能获取文件内容的想法,但我更喜欢在初始实例上这样做。

为了避免为每个文件连接/登录,请使用ftp_get并重用您的连接ID($conn_id):

foreach ($files as $file)
{
    // Full path to a remote file
    $remote_path = "DirectoryName/$file";
    // Path to a temporary local copy of the remote file
    $temp_path = tempnam(sys_get_temp_dir(), "ftp");
    // Temporarily download the file
    ftp_get($conn_id, $temp_path, $remote_path, FTP_BINARY);
    // Read the contents of temporary copy
    $contents = file_get_contents($temp_path);
    $content[$file] = $contents;
    // Discard the temporary copy
    unlink($temp_path);
}

(您应该添加一些错误检查。)