首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用cURL从网页中获取html,并使用preg-replace删除html

使用cURL从网页中获取html,并使用preg-replace删除html
EN

Stack Overflow用户
提问于 2012-05-04 20:54:03
回答 2查看 3.8K关注 0票数 3

我想从海盗湾得到统计数据,统计数据可以在TPB的以下div中找到:

代码语言:javascript
复制
<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>

这是我的代码:

代码语言:javascript
复制
<?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:

代码语言:javascript
复制
$data = preg_replace('/(.*?)(<div id="stats">)(.*?)(<\/div>)(.*?)/','$2',$data);

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

提前谢谢。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-05-04 21:08:03

忘了用正则表达式做屏幕擦除吧,改用domDocument吧,看看它有多简单:

代码语言:javascript
复制
<?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.
*/
?>
票数 6
EN

Stack Overflow用户

发布于 2012-05-04 21:10:02

为什么不使用preg_match()呢?

代码语言:javascript
复制
preg_match('/<div id="stats">(.*)<br \/>/Usi', $data, $m);
$stats = $m[1];
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10449200

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档