2014-10-20 17 views
1

请帮我检查一下这段代码。我想我的正则表达式写了一个问题,但我不知道如何解决它:为什么使用curl和正则表达式时数据为空

function get_data($url) 
{ 
    $ch = curl_init(); 
    $timeout = 5; 
    curl_setopt($ch,CURLOPT_URL,$url); 
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); 
    curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout); 
    $data = curl_exec($ch); 
    curl_close($ch); 
    return $data; 
} 

$content = get_data('http://ibongda.vn/lich-thi-dau-bong-da.hs'); 
$regex = '/<div id="zone-schedule-group-by-season">(.*)<\/div>/'; 
preg_match($regex, $content, $matches); 
$table = $matches[1]; 
print_r($table); 
+0

不使用正则表达式解析html – 2014-10-20 02:31:03

+0

该错误不在您的正则表达式中,它在您的设计中。正则表达式不是解析HTML的正确工具。我建议看看HTML解析器的'汤'家族之一 - 一目了然http://simplehtmldom.sourceforge.net/看起来是一个不错的选择。 – 2014-10-20 02:33:57

+0

我尝试simpledomhtml,但它很慢。我的托管有php 5.3,所以我不能使用最新的goutte版本。我不知道其他方式:( – 2014-10-20 02:34:52

回答

1

我建议不要使用正则表达式来解析这些。您可以使用HTML分析器,特别是使用xpath的DOMDocument

function get_data($url) 
{ 
    $ch = curl_init(); 
    $timeout = 5; 
    curl_setopt($ch,CURLOPT_URL,$url); 
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); 
    curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout); 
    $data = curl_exec($ch); 
    curl_close($ch); 
    return $data; 
} 

$content = get_data('http://ibongda.vn/lich-thi-dau-bong-da.hs'); 
$dom = new DOMDocument(); 
libxml_use_internal_errors(true); // handle errors yourself 
$dom->loadHTML($content); 
libxml_clear_errors(); 
$xpath = new DOMXpath($dom); 

$table_rows = $xpath->query('//div[@id="zone-schedule-group-by-season"]/table/tbody/tr[@class!="bg-gd" and @class!="table-title"]'); // these are the rows of that table 

foreach($table_rows as $rows) { // loop each tr 
    foreach($rows->childNodes as $td) { // loop each td 
     if(trim($td->nodeValue) != '') { // don't show empty td 
      echo trim($td->nodeValue) . '<br/>'; 
     } 
    } 
    echo '<hr/>'; 
} 
+2

我建议你链接到十亿个重复项之一;-)优先于回答 – 2014-10-20 02:32:32

+0

如何从中获取html元素$表?我echo $ table-> item(0) - > nodeValue,但我只得到文本。 – 2014-10-20 03:00:30

+0

@Ghost没错!非常感谢:) – 2014-10-20 03:13:58

2

我建议不要使用这个正则表达式。您应该使用DOM执行此任务。

你的正则表达式的问题正在运行到换行符序列中,它将匹配到<</div>之间,继续保持回溯并失败。回溯是匹配失败时匹配过程中正则表达式所做的事情。您需要使用s(dotall)修饰符,它强制点也匹配换行符。

$regex = '~<div id="zone-schedule-group-by-season">(.*?)</div>~s'; 
+0

我会遵循DOM,非常感谢:)我得到了它:) – 2014-10-20 03:24:04

相关问题