PHP cURL,读取远程文件并将内容写入本地文件 [英] PHP cURL, read remote file and write contents to local file

查看:93
本文介绍了PHP cURL,读取远程文件并将内容写入本地文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想连接到远程文件并将远程文件的输出写入本地文件,这是我的功能:

I want to connect to a remote file and writing the output from the remote file to a local file, this is my function:

function get_remote_file_to_cache()
{

    $the_site="http://facebook.com";

    $curl = curl_init();
    $fp = fopen("cache/temp_file.txt", "w");
    curl_setopt ($curl, CURLOPT_URL, $the_site);
    curl_setopt($curl, CURLOPT_FILE, $fp);

    curl_setopt($curl,  CURLOPT_RETURNTRANSFER, TRUE);

    curl_exec ($curl);

    $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    if($httpCode == 404) {
        touch('cache/404_err.txt');
    }else
    {
        touch('cache/'.rand(0, 99999).'--all_good.txt');
    }

    curl_close ($curl);
}

它在缓存"目录中创建两个文件.目录,但问题是它没有将数据写入"temp_file.txt",为什么?

It creates the two files in the "cache" directory, but the problem is it does not write the data into the "temp_file.txt", why is that?

推荐答案

您需要使用 fwrite 显式写入文件代码> ,将您之前创建的文件句柄传递给它:

You need to explicitly write to the file using fwrite, passing it the file handle you created earlier:

if ( $httpCode == 404 ) {
    ...
} else {
    $contents = curl_exec($curl);
    fwrite($fp, $contents);
}

curl_close($curl);
fclose($fp);

这篇关于PHP cURL,读取远程文件并将内容写入本地文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆