CSS Guy
CSS Guy

Reputation: 1984

I want to load specific div form other website in php

I have a problem to load specific div element and show on my page using PHP. My code right now is as follows:

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

I want it to load id="results-data" and show it on my page.

Upvotes: 3

Views: 9889

Answers (2)

cgvector
cgvector

Reputation: 927

You won't be able to manipulate the URL to get only a portion of the page. So what you'll want to do is grab the page contents via the server-side language of your choice and then parse the HTML. From there you can grab the specific DIV you are looking for and then print that out to your screen. You could also use to remove unwanted content.

With PHP you could use file_get_contents() to read the file you want to parse and then use DOMDocument to parse it and grab the DIV you want.

Here's the basic idea. This is untested but should point you in the right direction:

$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;
    }
}

Upvotes: 9

Sarfraz
Sarfraz

Reputation: 382909

You should use some html parser. Take a look at PHPQuery, here is how you can do it:

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;

Check it out here:

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

Also see their selectors' documentation.

Upvotes: 2

Related Questions