Archive

Posts Tagged ‘page’

Extract Links From A HTML File With PHP

March 6th, 2008 1 comment

Use the following function to extract all of the links from a HTML string.

function linkExtractor($html){
 $linkArray = array();
 if(preg_match_all('/<a\s+.*?href=[\"\']?([^\"\' >]*)[\"\']?[^>]*>(.*?)<\/a>/i',$html,$matches,PREG_SET_ORDER)){
  foreach($matches as $match){
   array_push($linkArray,array($match[1],$match[2]));
  }
 }
 return $linkArray;
}

To use it just read a web page or file into a string, and pass that string to the function. The following example reads a web page using the PHP CURL functions and then passes the result into the function to retrieve the links.

$url = 'http://www.talkincode.com';
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.12) Gecko/20080201 Firefox/2.0.0.12');
curl_setopt($ch,CURLOPT_HEADER,0);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_FOLLOWLOCATION,0);
curl_setopt($ch,CURLOPT_TIMEOUT,120);
$html = curl_exec($ch);
curl_close($ch);
echo '<pre>'.print_r(linkExtractor($html),true).'<pre>';

The function will return an array, with each element being an array containing the link location and the text that the link contains.

Categories: PHP Tags: , , , , , , ,

Display WordPress Feeds On Your Site With SimplePie

February 20th, 2008 6 comments

You can display your latest WordPress posts anywhere on your site by using an RSS reader called SimplePie and a few lines of code. SimplePie is a fast and efficient RSS reader, and it will also cache feeds to reduce the amount of processing time taken.

Download simple pie from the website and upload the simplepie.inc file to your web server. Next include the following section of code anywhere on your site that you want to display the latest post on.

<?php
require_once('simplepie.inc');
 
$feed = new SimplePie();
$feed->set_feed_url('http://www.example.com/feed');
 
$feed->init();
 
echo '<ul>';
 
// Limit the items to be shown
$i = 1;
foreach($feed->get_items() as $item){
 if($i<3){
  echo '<li><a href="'.$item->get_permalink().'">'.$item->get_title().'</a><br />'. "\n";
  echo substr($item->get_description(),0,180).'...</li>'."\n";
  $i++;
 }
}
echo '</ul>';
?>

You can also pull out categories by setting the feed URL to something like this.

http://www.example.co.uk/category/example/feed

This will allow you to display a page will posts from different categories.

Of course you can use this technique on any RSS generating blog platform, it doesn’t have to be WordPress, but it is much better than trying to figure out database connections and the like.

Categories: PHP Tags: , , , , , ,