我是学习php static function
的新手。我想构建一个函数,从某个url卷曲一些内容,然后处理php regex以获得我需要的东西。这是我的代码,但卷曲部分运行两次。如何修改它以便缩短运行时间?
$url = 'www.php.net/archive/2012.php';
if (!$url){
exit;
}
echo TestClass::getTitle1($url);
echo '<hr />';
echo TestClass::getTitle2($url);
class TestClass
{
static function getTitle1($url)
{
$data = self::getHtml($url);// run in first time
preg_match("/(<h1.*>)(.*)(<\/h1>)/",$data,$h1tags);
$h1 = $h1tags[0];
if (!$h1) return false;
return $h1;
}
static function getTitle2($url)
{
$data = self::getHtml($url);// run in second time
preg_match("/(<h2.*>)(.*)(<\/h2>)/",$data,$h2tags);
$h2 = $h2tags[0];
if (!$h2) return false;
return $h2;
}
static function getHtml($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$htmls = curl_exec($ch);
curl_close($ch);
if (!$htmls) return false;
return $htmls;
}
}
答案 0 :(得分:0)
像评论一样传递h1 / h2作为函数的参数并重写你的替换函数。或者在外面运行curl并将结果传递给replace函数。
答案 1 :(得分:0)
就像其他人告诉你的那样,不要重复自己并使用参数。
但是你需要将来可能使用的另一个类的方法(在一个以上的不同函数中使用一次性调用数据)我已经为你编辑了
<?php
class TestClass{
protected static $data;
static function getTitle1($url){
//check if $data is set or not
$data = self::$data ? self::$data : self::getHtml($url);
//do your code here
preg_match("/(<h1.*>)(.*)(<\/h1>)/",$data,$h1tags);
$h1 = $h1tags[0];
if (!$h1) return false;
return $h1;
}
static function getTitle2($url){
//check if $data is set or not
$data = self::$data ? self::$data : self::getHtml($url);
//do your code here
preg_match("/(<h1.*>)(.*)(<\/h1>)/",$data,$h1tags);
$h1 = $h1tags[0];
if (!$h1) return false;
return $h1;
}
static function getHtml($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$htmls = curl_exec($ch);
curl_close($ch);
if (!$htmls) return false;
//ADD THIS LINE TO YOUR CODE AS WELL
self::$data = $htmls;
return $htmls;
}
}
$url = 'www.php.net/archive/2012.php';
$class = new TestClass();
echo $class->getTitle1($url);
echo '<hr />';
echo $class->getTitle2($url);
?>