Tuesday 10 April 2012

Parsing bookmark files using PHP and writing it out as an HTML link

Here's a code example of something I knocked together to import Windows .url shortcut files to a MySQL database on my home-server system that I'm building.

The shortcut files are actually just text, so you can read them really easily..  
They just contain a header, then the URL.. For example:

[InternetShortcut]
URL=http://www.hackerspace.co.uk


Here's a PHP code snippet... 


//  Create a function and give it the filename of the URL file.. 

function readurl($filename)
{

// Pull the .url off the end.. 
$filenamebits= explode(".url",$filename);

// Create a "Link Description" from the filename
$linkdesc=$filenamebits[0];

// Open the file to get at it's juicy contents
$file = fopen("$filename","r");

// Set up a counter
$linecount=0;

// Set up a "While there's still stuff in the file" loop
while (!feof($file) ) {

// Open the file and get stuff from it, line by line
$line_of_text = fgets($file);

// If you're on line number 1... 
if ($linecount==1)

// Explode the line of text into pieces
$pieces = explode("=", $line_of_text);

// Extract the bits we want and wrap it in some friendly HTML
$URLTOADD="<a href=\"$pieces[1]\">$linkdesc</a>";

// You can either then write this string out to the screen, or like I do, fire it 
// into a database for later use

}

// Increment the line count
$linecount++;

}

// Close the file. Otherwise the operating system gets cross. Probably. 
fclose($file);

}

No comments:

Post a Comment

Concatenating CSVs the easy way

I was recently asked how to 'merge' a few CSV files into one, and if there was a script or tool that could do that. Lets say you h...