Skip to content Skip to sidebar Skip to footer

How Do I Display Content Grabbed From External Websites?

How do I grab pieces of content from external websites and display them on my website? (Similar to what an RSS feed or other aggregator does). For example, say I want to display it

Solution 1:

I would not recommend regex for parsing HTML. PHP 5+ comes with a parser which you can use as shown below.

$content = file_get_contents('test.html');
$doc = 
<<<DOC
$content
DOC;
$dom = new DOMDocument();
$dom->loadHTML($doc);
$h2Tags = $dom->getElementsByTagName("h2");
$pTags = $dom->getElementsByTagName("p");
foreach($h2Tagsas$h2 ) {
    //do something
}

foreach($pTagsas$p ) {
if($p->getAttribute("class") == "date") {
    //do something
}

}

$h2 is of type DOMElement. It inherits DOMNode. So you can use nodeValue property to access the values. In the above example, you can write $h2->nodeValue to access the content.

Solution 2:

you can try this library http://simplehtmldom.sourceforge.net/

then just:

foreach($dom->find('p[class=date]'as$p) {
  $date = $p->innertext;
}

this would give you the contents of

or you do it more globaly and dig through with stripos

foreach($dom->find('p') as$p) {
  if(stripos($p->class, 'date') !== false) {
    //do something
  }
}

Solution 3:

Here's an example for using cURL:

http://tr2.php.net/manual/en/curl.examples-basic.php

and check if you are getting data before applying preg_match. If you get some, then it's the regex which causes your problem.

Post a Comment for "How Do I Display Content Grabbed From External Websites?"