cURL下载进度在PHP [英] cURL download progress in PHP

查看:385
本文介绍了cURL下载进度在PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对cURL很新,所以我一直在努力工作几个小时。我试图下载一个网站的源代码在iframe使用cURL和在加载时显示其中有多少加载。到目前为止,我已成功下载源,而不显示加载进度。你能解释一下如何显示下载进度吗?如果没有cURL,我将逐字节读取文件,并将下载的字节总数除以文件的总大小。如何在cURL中这样做,因为它读取源作为一个整体? (至少我认为这是唯一的方法,不确定)这里是我到目前为止:

I'm pretty new to cURL so I've been struggling with this one for hours. I'm trying to download the source of a website in an iframe using cURL and while it's loading to show how much of it is loaded. So far I have successfully downloaded the source without showing the loading progress. Can you explain how to show the download progress? Without cURL I would read the file byte by byte and divide the total amount of downloaded bytes with the total size of the file. How can this be done in cURL since it reads the source as a whole? (at least I think that this is the only way, not sure) Here's what I've got so far:

/* Download source */
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $adress);  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0); 
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
$html = curl_exec($ch);
curl_close($ch); 


推荐答案

您需要的是

<?php
ob_start();

echo "<pre>";
echo "Loading ...";

ob_flush();
flush();

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://stackoverflow.com");
//curl_setopt($ch, CURLOPT_BUFFERSIZE,128);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, 'progress');
curl_setopt($ch, CURLOPT_NOPROGRESS, false); // needed to make progress function work
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
$html = curl_exec($ch);
curl_close($ch);


function progress($resource,$download_size, $downloaded, $upload_size, $uploaded)
{
    if($download_size > 0)
         echo $downloaded / $download_size  * 100;
    ob_flush();
    flush();
    sleep(1); // just to see effect
}

echo "Done";
ob_flush();
flush();

?>

这篇关于cURL下载进度在PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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