【发布时间】:2018-04-01 19:52:37
【问题描述】:
我一直在努力提高我的编程技能,到目前为止我都是在线学习的。但我找不到避免重复代码的方法。这是我的代码:
public function Curl($page, $check_top = 0, $pages = 1, $pagesources = array()){
//$page is the URL
//$check_top 0 = false 1 = true. When true it needs to check both false & true
//$pages is the amount of pages it needs to check.
$agent = "Mozilla/5.0 (Windows NT x.y; Win64; x64; rv:10.0) Gecko/20100101 Firefox/10.0";
try{
for($i = 0; $i < $pages; $i++){
$count = $i * 25; //Page 1 starts at 0, page 2 at 25 etc..
$ch = curl_init($page . "/?count=" . $count);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$pagesource = curl_exec($ch);
$pagesources[] = $pagesource;
}
if($check_top == 1){
for($i = 0; $i < $pages; $i++){
$count = $i * 25;
$ch = curl_init($page . "/top/?sort=top&t=all&count=" . $count);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$pagesource = curl_exec($ch);
$pagesources[] = $pagesource;
}
}
} catch (Exception $e){
echo $e->getMessage();
}
return $pagesources;
}
我正在尝试做的事情: 我想从特定页面范围(例如 1 到 5 页)中获取 HTML 页面源。有首页和标准页面,我想从页面范围内获取来源。所以我的代码工作正常,但很明显;一定有更好的办法。
【问题讨论】:
-
可以通过将重复代码包装在函数或类中来避免重复代码。只需为 curl 操作编写一个函数。
-
例如,我将如何处理这个问题?我需要传递的数据是动态的。 2 个独立的功能,一个用于首页,一个用于标准页面? @Marcel
标签: php code-duplication