我有以下PHP代码,我发现here:
function download_xml()
{
$url = 'http://tv.sygko.net/tv.xml';
$ch = curl_init($url);
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
echo("curl_exec was succesful"); //This never gets called
curl_close($ch);
return $data;
}
$my_file = 'tvdata.xml';
$handle = fopen($my_file, 'w');
$data = download_xml();
fwrite($handle, $data);
我要做的是在指定的网址下载xml并将其保存到磁盘。但是,它会在约80%完成时停止,并且在echo
调用后永远不会到达curl_exec
来电。我不确定为什么,但我相信这是因为内存不足。因此,我想问一下,每次下载4kb时,是否可以将curl写入文件。如果这是不可能的,有人知道一种方法来获取存储在url下的xml文件下载并使用php存储在我的磁盘上吗?
非常感谢, BEN。
修改: 这是现在的代码,它不起作用。它将数据写入文件,但仍然只占文档的80%左右。也许不是因为它超过记忆而是其他原因?我真的不敢相信将文件从URL复制到光盘很难......
<?
$url = 'http://tv.sygko.net/tv.xml';
$my_file = fopen('tvdata.xml', 'w');
$ch = curl_init($url);
$timeout = 300;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FILE, $my_file);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_BUFFERSIZE, 4096);
curl_exec($ch) OR die("Error in curl_exec()");
echo("got to after curl exec");
fclose($my_file);
curl_close($ch);
?>
答案 0 :(得分:5)
这里有一个完整的例子:
public function saveFile($url, $dest) {
if (!file_exists($dest))
touch($dest);
$file = fopen($dest, 'w');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, 'progressCallback');
curl_setopt($ch, CURLOPT_BUFFERSIZE, (1024*1024*512));
curl_setopt($ch, CURLOPT_NOPROGRESS, FALSE);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
curl_setopt($ch, CURLOPT_FILE, $file);
curl_exec($ch);
curl_close($ch);
fclose($file);
}
?>
秘密在于将CURLOPT_NOPROGRESS设置为FALSE,然后,CURLOPT_BUFFERSIZE将为每个到达的CURLOPT_BUFFERSIZE字节生成回调报告。值越小,报告的频率越高。这也取决于你的下载速度等,所以不要指望每隔X秒报告一次,因为它会报告接收/传输的每个X字节。
答案 1 :(得分:3)
您的超时设置为5秒,可能会太短,具体取决于文档的文件大小。尝试将其增加到10-15只是为了确保它有足够的时间来完成转移。
答案 2 :(得分:2)
有一个名为CURELOPT_FILE的选项,允许您指定curl应写入的文件处理程序。我很确定它会做“正确”的事情,并在阅读时“写”,避免你的记忆问题
$file = fopen('test.txt', 'w'); //<--------- file handler
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'http://example.com');
curl_setopt($ch, CURLOPT_FAILONERROR,1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
curl_setopt($ch, CURLOPT_FILE, $file); //<------- this is your magic line
curl_exec($ch);
curl_close($ch);
fclose($file);
答案 3 :(得分:1)
curl_setopt CURLOPT_FILE - 应该将传输写入的文件。默认值为STDOUT(浏览器窗口)