3

我在使用 PHP 加载特定 div 元素并在我的页面上显示时遇到问题。我现在的代码如下:

<?php
    $page = file_get_contents("http://www.bbc.co.uk/sport/football/results");
    preg_match('/<div id="results-data" class="fixtures-table full-table-medium">(.*)<\/div>/is', $page, $matches);
    var_dump($matches);
?>

我希望它加载 id="results-data" 并将其显示在我的页面上。

4

2 回答 2

7

您将无法操纵 URL 以仅获取页面的一部分。因此,您要做的是通过您选择的服务器端语言获取页面内容,然后解析 HTML。从那里您可以获取您正在寻找的特定 DIV,然后将其打印到您的屏幕上。您还可以用来删除不需要的内容。

使用 PHP,您可以使用file_get_contents()读取要解析的文件,然后使用DOMDocument解析它并获取所需的 DIV。

这是基本的想法。这是未经测试的,但应该为您指明正确的方向:

$page = file_get_contents('http://www.bbc.co.uk/sport/football/results');
$doc = new DOMDocument();
$doc->loadHTML($page);
$divs = $doc->getElementsByTagName('div');
foreach($divs as $div) {
    // Loop through the DIVs looking for one withan id of "content"
    // Then echo out its contents (pardon the pun)
    if ($div->getAttribute('id') === 'content') {
         echo $div->nodeValue;
    }
}
于 2012-06-12T06:10:52.423 回答
2

您应该使用一些 html 解析器。看看 PHPQuery,你可以这样做:

require_once('phpQuery/phpQuery.php');
$html = file_get_contents('http://www.bbc.co.uk/sport/football/results');
phpQuery::newDocumentHTML($html);
$resultData = pq('div#results-data');
echo $resultData;

在这里查看:

http://code.google.com/p/phpquery

另请参阅他们的选择器文档。

于 2012-05-27T19:12:34.117 回答