我有以下PHP代码,我在这里找到:
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);
Run Code Online (Sandbox Code Playgroud)
我要做的是在指定的URL下载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);
?>
Run Code Online (Sandbox Code Playgroud)
这是一个完整的例子:
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);
}
?>
Run Code Online (Sandbox Code Playgroud)
秘诀在于将CURLOPT_NOPROGRESS设置为FALSE,然后,CURLOPT_BUFFERSIZE将为每个到达的CURLOPT_BUFFERSIZE个字节生成回调报告.值越小,报告的频率越高.这还取决于您的下载速度等,因此不要指望每隔X秒报告一次,因为它将报告接收/传输的每个X字节.
| 归档时间: |
|
| 查看次数: |
11744 次 |
| 最近记录: |