2012-05-27 66 views
2

我有一个问题,加载特定的div元素,并显示在我的网页上使用PHP。我现在的代码如下:我想加载特定的div格式其他网站在PHP

<?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”并将其显示在我的页面上。

+0

你得到什么错误? – Norse

+0

你尝试了什么,结果是什么? – Hidde

+1

问题到底在哪里?你有正则表达式。 – Ahatius

回答

6

您将无法操纵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; 
    } 
} 
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

Also see their selectors' documentation.

+0

我得到以下错误 警告:file_get_contents(http://www.bbc .co.uk/sport/football/results)[function.file-get-contents]:无法打开流:....一段时间后回应,或者建立连接失败,因为已连接 –

+0

@Rizwanabbasi:这是错误bbc方面,有服务器故障或其他原因。 – Sarfraz

相关问题