0

我是学习新手,php static function我想构建一个函数,从某个 url 卷曲一些内容,然后处理 php regex 以获得我需要的东西。这是我的代码,但 curl 部分运行了两次。如何修改它以缩短运行时间?

$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;
    }
}
4

2 回答 2

0

就像评论一样,将 h1/h2 作为参数传递给您的函数并重写您的替换函数。或者在外面运行 curl 并将结果传递给您的替换函数。

于 2012-11-10T14:01:47.207 回答
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);
?>
于 2012-11-10T14:34:25.610 回答