【问题标题】:Why get data is empty when using curl and regex [duplicate]为什么使用curl和regex时获取数据为空[重复]
【发布时间】:2014-10-20 02:27:22
【问题描述】:

请帮我检查这段代码。我认为我写的正则表达式有问题,但我不知道如何解决:

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);

【问题讨论】:

  • 不要用正则表达式解析html
  • 错误不在您的正则表达式中,而在您的设计中。正则表达式不是解析 HTML 的正确工具。我建议查看 HTML 解析器的“汤”系列之一 - 乍一看simplehtmldom.sourceforge.net 看起来是个不错的选择。
  • 我尝试了 simpledomhtml,但速度很慢。我的主机有 php 5.3,所以我不能使用最新的 goutte 版本。我不知道其他方式:(
  • 一旦输入只是 DOM,使用 DOM 永远不会比 RegExp 慢。

标签: php html regex curl


【解决方案1】:

我建议不要为此使用正则表达式。你应该使用DOM 来完成这个任务。

您的正则表达式的问题是遇到换行符序列,它将匹配到&lt;/div&gt; 中的&lt;,不断回溯并失败。回溯是正则表达式在匹配过程中匹配失败时所做的事情。您需要使用 s (dotall) 修饰符来强制点匹配换行符。

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

【讨论】:

  • 我会关注 DOM,非常感谢 :) 我明白了 :)
【解决方案2】:

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

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/>';
}

【讨论】:

  • 我建议您链接到十亿个重复项之一;-) 优先回答
  • 如何从 $table 中获取 html 元素?我回显 $table->item(0)->nodeValue 但我只得到文本。
  • @Ghost 没错!非常感谢:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-10
  • 1970-01-01
  • 2016-02-06
  • 1970-01-01
  • 1970-01-01
  • 2016-02-18
相关资源
最近更新 更多