PHP – Read/Parse an Exported Bookmarks File

Since I couldn’t find anything like this online, I thought it might help someone else.

<?php 

$file = "ps_bookmarks.html"; 

$handle = @fopen($file, "r");

if ($handle) {
	
    while (!feof($handle)) {
		
        $line = trim(fgets($handle, 4096));
		
		if ($line) {
			
			// If end of items in folder, then remove last folder from category list
			
			if (eregi("</dl>",$line)) {
				
				$tmp = array_pop($catlist);				
				
			}
			
			
			if (eregi("<dt>",$line) && !eregi("href",$line)) {
				
				$catlist[] = ucfirst(strip_tags($line));
					
			}
			
			
			if (eregi("href",$line)) {
				
				preg_match("/href="([^"]+)"/i",$line,$matches);
				
				$url = $matches[1];
				
				$title = strip_tags($line);
				
				foreach ($catlist as $k => $v) {
					echo "$v/";
				}
				
				echo " - ";
				
				echo $title;
				
				echo " - ";
				
				echo $url;
				
				echo "<br>";
			
			}				
			
		}
		
    }
	
    fclose($handle);
	
}

?>

I used an exported Chrome bookmarks file.  The kind that starts with:

<!DOCTYPE NETSCAPE-Bookmark-file-1>

Code I found online was broken, so I made my own bookmarks parser.  I did modify the bookmarks file to help get the output I wanted (I have hundreds of bookmarks all categorized, so I deleted huge swathes of links I no longer wanted)  and I modified this code before I posted it to remove bits that were for my particular setup, but it’s all generally there.  I’m sure a clever programmer could take this and make something slick.

This is the rough draft.  I wanted to get my bookmarks into a database and wanted to keep the organization intact. This meant tracking the folders and subfolders, and this does the job.

Leave a comment

You must be logged in to post a comment.