2012-05-27 62 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

相關問題