3

我想从 The Pirate Bay 获取统计数据,可以在 TPB 的以下 div 中找到统计数据:

<div id="stats">5.695.184 registered users Last updated 14:46:05.<br />35.339.741 peers (25.796.820 seeders + 9.542.921 leechers) in 4.549.473 torrents.<br />    </div>

这是我的代码:

<?php
    $ch = curl_init();
    $timeout = 5;
    curl_setopt($ch, CURLOPT_URL,"http://thepiratebay.se"); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
    curl_setopt($ch,CURLOPT_COOKIE,"language=nl_NL; c[thepiratebay.se][/][language]=nl_NL");
    $data=curl_exec($ch);
    $data = preg_replace('/(.*?)(<div id="stats">)(.*?)(<\/div>)(.*?)/','$2',$data);
    echo $data; 
    curl_close($ch); 
    exit;
?>

如您所见,我使用以下preg-replace模式来剥离 HTML:

$data = preg_replace('/(.*?)(<div id="stats">)(.*?)(<\/div>)(.*?)/','$2',$data);

但这行不通。我得到了整个 TPB 页面,而不仅仅是统计数据。有人有答案吗?

提前致谢。

4

2 回答 2

6

忘记使用正则表达式进行屏幕报废,改用domDocument,看看它是多么简单:

<?php 
function curl_get($url){
    $useragent = 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.0.3705; .NET CLR 1.1.4322; Media Center PC 4.0)';
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,5);
    curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
    curl_setopt($ch,CURLOPT_COOKIE,"language=nl_NL; c[thepiratebay.se][/][language]=nl_NL");
    $data=curl_exec($ch);
    curl_close($ch);
    return $data;
}

function get_pb_stats(){
    $html = curl_get("http://thepiratebay.se");
    // Create a new DOM Document
    $xml = new DOMDocument();

    // Load the html contents into the DOM
    @$xml->loadHTML($html);

    $return = trim($xml->getElementById('stats')->nodeValue);
    //regex to add the brake tag after 15:04:05. 
    $return = preg_replace('/\d{2}[:]\d{2}[:]\d{2}[.]/','${0}<br />',$return);
    return $return;
}

echo get_pb_stats();

/*
5.695.213 geregistreerde gebruikers Laatste update 15:04:05.<br />35.505.322 peers (25.948.185 seeders + 9.557.137 leechers) in 4.546.560 torrents.
*/
?>
于 2012-05-04T13:08:03.090 回答
0

为什么不使用 preg_match()?

preg_match('/<div id="stats">(.*)<br \/>/Usi', $data, $m);
$stats = $m[1];
于 2012-05-04T13:10:01.620 回答