-2

我有一个 php 脚本正在运行并使用 cURL 来检索我想检查是否存在某些文本的网页内容。

现在它看起来像这样:

for( $i = 0; $i < $num_target; $i++ ) {
    $ch = curl_init();
    $timeout = 10;
    curl_setopt ($ch, CURLOPT_URL,$target[$i]);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt ($ch, CURLOPT_FORBID_REUSE, true);
    curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $url = curl_exec ($ch);
    curl_close($ch);

    if (preg_match($text,$url,$match)) {
        $match[$i] = $match;
        echo "text" . $text . " found in URL: " . $url . ": " . $match .;

        } else {
        $match[$i] = $match;
        echo "text" . $text . " not found in URL: " . $url . ": no match";
        }
}

我想知道是否可以使用一种特殊的 cURL 设置来使其更快(我在 php 手册中选择了对我来说似乎最好的选项,但我可能忽略了一些可以提高脚本速度和性能的选项)。

然后我想知道使用 cgi、Perl 或 python(或其他解决方案)是否会比 php 更快。

提前感谢您的任何帮助/建议/建议。

4

1 回答 1

3

您可以使用curl_multi_init.... 它允许并行处理多个 cURL 句柄。

例子

$url = array();
$url[] = 'http://www.huffingtonpost.com';
$url[] = 'http://www.yahoo.com';
$url[] = 'http://www.google.com';
$url[] = 'http://technet.microsoft.com/en-us/';

$start = microtime(true);
echo "<pre>";
print_r(checkLinks($url, "Azure"));
echo "<h1>", microtime(true) - $start, "</h1>";

输出

Array
(
    [0] => http://technet.microsoft.com/en-us/
)

1.2735739707947 <-- Faster

使用的功能

function checkLinks($nodes, $text) {
    $mh = curl_multi_init();
    $curl_array = array();
    foreach ( $nodes as $i => $url ) {
        $curl_array[$i] = curl_init($url);
        curl_setopt($curl_array[$i], CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl_array[$i], CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)');
        curl_setopt($curl_array[$i], CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($curl_array[$i], CURLOPT_TIMEOUT, 15);
        curl_multi_add_handle($mh, $curl_array[$i]);
    }
    $running = NULL;
    do {
        usleep(10000);
        curl_multi_exec($mh, $running);
    } while ( $running > 0 );
    $res = array();
    foreach ( $nodes as $i => $url ) {
        $curlErrorCode = curl_errno($curl_array[$i]);
        if ($curlErrorCode === 0) {
            $info = curl_getinfo($curl_array[$i]);
            if ($info['http_code'] == 200) {
                if (stripos(curl_multi_getcontent($curl_array[$i]), $text) !== false) {
                    $res[] = $info['url'];
                }
            }
        }
        curl_multi_remove_handle($mh, $curl_array[$i]);
        curl_close($curl_array[$i]);
    }
    curl_multi_close($mh);
    return $res;
}
于 2012-10-15T10:17:05.923 回答