Skip to main content

Tip: Manipulate del.icio.us bookmarks with PHP

Use the del.icio.us REST API with PHP and PEAR

Vikram Vaswani, Founder, Melonfire
Vikram Vaswani is the founder and CEO of Melonfire, a consulting services firm with special expertise in open-source tools and technologies. He is also the author of the books PHP Programming Solutions and How to do Everything with PHP and MySQL.

Summary:  The del.icio.us service lets users collect and share bookmarks online. Manipulate these bookmarks with PEAR's Services_Delicious package that interfaces with the REST API of del.icio.us and build customized PHP applications.

View more content in this series

Date:  22 Jan 2008
Level:  Intermediate
Activity:  4131 views

Introduction

If you surf the Web with any degree of intensity, chances are you already know what del.icio.us is: a free online service that allows you to bookmark interesting Web sites and share them with other users. The service also allows users to "tag" bookmarks with keywords, and view the most popular bookmarks at any given time.

One cool feature of del.icio.us is the ability to access your bookmark list through a REST-based API, and integrate this list into your own XML-aware application. In most cases, this involves writing application-level code to communicate with the del.icio.us REST API, send requests, and parse responses. However, if your application is a PHP application, you can reduce some of the work in this process if you use Services_Delicious, a package from the PHP Extension and Application Repository (PEAR).

The Services_Delicious package provides an API to communicate with the del.icio.us REST API, create and transmit requests, and parse and decode XML responses. As such, it provides a robust, easy-to-use widget to view, add, edit or delete del.icio.us bookmarks from within any PHP application. This tip provides a brief overview of the package, with code illustrations of how you can accomplish these basic tasks.


Installation

The Services_Delicious package is maintained by Stephan Schmidt and Tatsuya Tsuruoka, and released to the PHP community under a PHP license. The easiest way to install it is with the automated PEAR installer, which should have been included by default with your PHP build. To install it, simply issue the following command at your shell prompt:

shell> pear install Services_Delicious

The PEAR installer will now connect to the PEAR package server, download the package, and install it to the appropriate location on your system. This tip uses Services_Delicious V0.5.0.

To install the package by hand, visit its home page, download the source code archive, and manually uncompress the files to the desired location. Note that this manual installation process presupposes some knowledge of PEAR's package organization structure.

Services_Delicious depends on two other PEAR packages: the HTTP_Request package and the XML_Serializer package. With the PEAR automated installer, you can install these package as described previously; alternatively, you'll find links to the package files from the Resources of this tip. It's worth noting that in my development, I found that the HTTP_Request package sometimes failed to function correctly on Windows® and so the examples in this tutorial assume a *NIX development environment.

Services_Delicious also requires that you install OpenSSL and the OpenSSL extension of PHP in your PHP development environment. In *NIX environments, it may be necessary to recompile PHP with support for this extension. Find links to the OpenSSL Web site and further information on activating PHP's OpenSSL extension from the Resources.

Finally, the examples in this tip assume that you already have an account with del.icio.us, possibly with a few bookmarks added to it. In case you don't, you should sign up with the service—it's free—and seed your account with some entries. You'll find a link to the service's sign-up page in the Resources section of this tip.


Retrieving bookmarks

Before you dive into Services_Delicious, a few words about the del.icio.us API are in order. As with all REST-based services, the API works over HTTP, using HTTP Basic authentication to verify a user's credentials before granting access. It includes methods to add and delete bookmarks, retrieve a user's bookmark list, and retrieve (or rename) a user's tags.

To see the API in action, try accessing the URL https://api.del.icio.us/v1/posts/recent in your favourite Web browser. This REST method returns a list of the user's most recent posts. You will be asked to sign in with your del.icio.us user credentials; once done, you should see the raw XML response to this method, which contains a list of recent bookmarks. It will look something like Listing 1:


Listing 1. An XML response packet from del.icio.us
                                
<?xml version='1.0' standalone='yes'?>
<posts tag="" user="someuser">
  <post href="http://www.kernel.org/" description="The Linux Kernel Archives" 
   hash="7dae6d24e3f8c6c3c3aa1b05ce5bfe94" tag="linux kernel opensource" 
   time="2007-12-04T09:03:25Z" />
  <post href="http://www.everythingphpmysql.com/" description="How to 
   do Everything with PHP & MySQL - Vikram Vaswani" 
   hash="8c9c6572c70cb3de3fa93b87269a8d79" 
   tag="book development php mysql web beginner" time="2007-12-04T09:02:47Z" />
  <post href="http://www.mysql-tcr.com/" description="MySQL: The Complete 
   Reference - Vikram Vaswani" hash="c8d99b00cfb9a1af9d59bbc6c46848cd" 
   tag="mysql php book" time="2007-12-04T09:02:21Z" />
  ...
</posts>
        

Figure 1 shows this output in Mozilla Firefox:


Figure 1. An XML response packet from del.icio.us, as seen in Mozilla Firefox
An XML response packet from del.icio.us, as seen in Mozilla Firefox

Listing 2 demonstrates how to replicate this action with Services_Delicious, in the context of a PHP application:


Listing 2. Retrieving bookmarks
                                
<?php
// include class file
include_once 'Services/Delicious.php';

// initialize object
$sdObj = new Services_Delicious('someuser', 'somepass');

// get recent posts from del.icio.us
print_r($sdObj->getRecentPosts());
?>
        

Remember to replace the dummy user name and password in this listing, and all subsequent ones, with actual values.

Listing 2 uses the Services_Delicious package of PHP to connect to the del.icio.us Web service and retrieve a list of recent posts. To begin, it reads the Services_Delicious class file and initializes an object instance of the Services_Delicious class. The user's del.icio.us user name and password are passed to the object constructor and used to perform HTTP authentication. Then, the object's getRecentPosts() method retrieves the user's most recently-submitted bookmarks, and the XML response is then parsed and converted into a nested series of PHP arrays.

Listing 3 demonstrates what the array returned by getRecentPosts() looks like:


Listing 3. An example PHP array containing retrieved bookmarks
                                
Array
(
    [0] => Array
        (
            [href] => http://www.kernel.org/
            [description] => The Linux Kernel Archives
            [hash] => 7dae6d24e3f8c6c3c3aa1b05ce5bfe94
            [tag] => Array
                (
                    [0] => linux
                    [1] => kernel
                    [2] => opensource
                )

            [time] => 2007-12-04T09:03:25Z
        )

    [1] => Array
        (
            [href] => http://www.everythingphpmysql.com/
            ...
        )
)
        

The foreach() loop in PHP makes it easy to reformat this array for HTML display. Listing 4 illustrates the process:


Listing 4. Formatting retrieved bookmarks as an HTML page
                                
<html>
  <head></head>
  <body>
    <h2>My Bookmarks</h2>
    <?php
    // include class file
    include_once 'Services/Delicious.php';
    
    // initialize object
    $sdObj = new Services_Delicious('someuser', 'somepass');
    
    // get recent posts from del.icio.us
    // print as bulleted list
    $posts = $sdObj->getRecentPosts();
    echo "<ul>\n";
    foreach ($posts as $p) {
      echo "  <li>\n";
      echo "    <a href=\"" . $p['href'] . "\">" . $p['description'] . "</a><br />\n";
      echo "    <span style=\"color:red\">" . implode(' ', $p['tag']) . "</span>\n";
      echo "  </li>\n";
    }
    echo "</ul>\n";
    ?>
  </body>
</html>
        

Listing 4 iterates over the array returned by getRecentPosts(), printing each element as a bulleted list item, with the corresponding tags listed below each item. Figure 2 shows what this output might look like:


Figure 2. An HTML document displaying bookmarks retrieved from del.icio.us
An HTML document displaying bookmarks retrieved from del.icio.us

Working with tags

The getTags() method returns a list of all tags used in a del.icio.us account, together with a count of how often each one is used. Listing 5 illustrates this method:


Listing 5. Retrieving user tags
                                
<html>
  <head></head>
  <body>
    <h2>My Tags</h2>
    <?php
    // include class file
    include_once 'Services/Delicious.php';
    
    // initialize object
    $sdObj = new Services_Delicious('someuser', 'somepass');
    
    // get tags from del.icio.us
    // print as table
    $tags = $sdObj->getTags();
    echo "<table border=\"1\">\n";
    foreach ($tags as $tag => $count) {
      echo "  <tr>\n";
      echo "    <td>$tag</td>\n";
      echo "    <td>$count</td>\n";
      echo "  </tr>\n";
    }
    echo "</table>\n";
    ?>
  </body>
</html>
        

And Figure 3 illustrates what the output might look like:


Figure 3. An HTML document displaying tags retrieved from del.icio.us
An HTML document displaying tags retrieved from del.icio.us

One you have a list of tags, use the getPosts() method to return all bookmarks that match one or more of these tags, by passing it an array of tag names as first argument. Listing 6 illustrates, returning only those bookmarks tagged with the keyword book:


Listing 6. Filtering bookmarks by tag
                                
<html>
  <head></head>
  <body>
    <h2>My Bookmarks</h2>
    <?php
    // include class file
    include_once 'Services/Delicious.php';
    
    // initialize object
    $sdObj = new Services_Delicious('someuser', 'somepass');
    
    // get recent posts from del.icio.us
    // tagged with 'book'
    // print as bulleted list
    $posts = $sdObj->getPosts(array('book'));
    echo "<ul>\n";
    foreach ($posts as $p) {
      echo "  <li>\n";
      echo "    <a href=\"" . $p['href'] . "\">" . $p['description'] . "</a><br />\n";
      echo "    <span style=\"color:red\">" . implode(' ', $p['tag']) . "</span>\n";
      echo "  </li>\n";
    }
    echo "</ul>\n";
    ?>
  </body>
</html>
        

Incidentally, you can also pass getRecentPosts() a similar array of tag names as first argument.


Adding and deleting bookmarks

Services_Delicious also lets you add and delete bookmarks to your del.icio.us account from within your PHP application, through its addPost() and deletePost() methods. To illustrate, consider Listing 7, which adds a new bookmark:


Listing 7. Adding a bookmark
                                
<?php
// include class file
include_once 'Services/Delicious.php';

// initialize object
$sdObj = new Services_Delicious('someuser', 'somepass');

// add a bookmark to del.icio.us
$ret = $sdObj->addPost('http://www.google.com/', 'My fav search engine', 
  null, 'search web cool', null, null);
if ($ret === true) {
  echo 'Bookmark added.';
} else {
  echo 'Bookmark could not be added.';
}
?>
        

The addPost() method accepts six parameters, of which only the first two are mandatory. The parameters are, in order of appearance:

  • The URL
  • A description of the URL link
  • An extended description of the URL link
  • Tags for the link
  • The date and time at which the URL was submitted
  • Whether or not the item is private

The return value of addPost() is Boolean, making it easy to check whether the item was successfully posted or not, and display an appropriate message to the user.

Want to remove a bookmark which has fallen out of favour? Listing 8 illustrates the necessary code:


Listing 8. Deleting a bookmark
                                
<?php
// include class file
include_once 'Services/Delicious.php';

// initialize object
$sdObj = new Services_Delicious('someuser', 'somepass');

// remove a bookmark from del.icio.us
$ret = $sdObj->deletePost('http://www.google.com/');
if ($ret === true) {
  echo 'Bookmark removed.';
} else {
  echo 'Bookmark could not be removed.';
}
?>
        

Removing a bookmark is even easier than adding one: simply provide deletePost() with the URL and bzzzt...it's gone!


A simple application

Now that you understand what Services_Delicious can do, how about tying it all up with a practical example? Listing 9 demonstrates a PHP-based del.icio.us bookmark manager, which uses the methods described in previous sections to let users view and add bookmarks interactively:


Listing 9. An interactive bookmark manager
                                
<html>
  <head></head>
  <body>
    <h2>My Bookmarks</h2>
    <?php
    // include class file
    include_once 'Services/Delicious.php';

    // use form submission
    // to add new bookmark
    if (isset($_POST['submit'])) {
      $url = trim($_POST['url']);
      $desc = trim($_POST['desc']);
      $tags = trim($_POST['tags']);
      $sdObj = new Services_Delicious('someuser', 'somepass');
      $ret = $sdObj->addPost($url, $desc, null, $tags, null, null);
      if ($ret === true) {
        echo 'Bookmark saved!';
      } else {
        echo 'Bookmark not saved!';
      }
      unset($sdObj);
    }

    // get recent posts from del.icio.us
    // print as bulleted list
    $sdObj = new Services_Delicious('someuser', 'somepass');
    $posts = $sdObj->getRecentPosts();
    echo "<ul>\n";
    foreach ($posts as $p) {
      echo "<li>\n";
      echo "<a href=\"" . $p['href'] . "\">" . $p['description'] . "</a><br />\n";
      echo "<span style=\"color:red\">" . implode(' ', $p['tag']) . "</span>\n";
      echo "</li>\n";
    }
    echo "</ul>\n";
    ?>

    <h2>Add New Bookmark</h2>
    <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
      URL *: <br /> <input type="text" name="url" size="30" /> <br />
      Description *: <br /> <input type="text" name="desc" size="30" /> <br />
      Tags: <br /> <input type="text" name="tags" size="30" /> <br />
      <input type="submit" name="submit" value="Save" />
    </form>
  </body>
</html>
        

Listing 9 makes use of two methods you've seen already:

  • The getRecentPosts() method, which lists recently-added bookmarks
  • The addPost() method, which accepts data from a form submission and updates the bookmark list accordingly

Figure 4 illustrates the main page of the application:


Figure 4. The HTML form for adding a new bookmark to del.icio.us
The HTML form for adding a new bookmark to del.icio.us

And Figure 5 shows the updated main page, after adding a new bookmark:


Figure 5. The new bookmark list from del.icio.us, after adding a bookmark
The new bookmark list from del.icio.us, after adding a bookmark

As these examples illustrate, the Services_Delicious package provides a neat PHP wrapper around the del.icio.us REST API. It's very useful if you try to mash up your del.icio.us data with data from other Web services, or simply build a customized interface to the del.icio.us service. Play with it, and see what you think!


Resources

Learn

Get products and technologies

  • The Services_Delicious package: Download a client for the REST-based Web service of del.icio.us to easily add, categorize, and share your collection of sites.

  • The XML_Serializer package: Download this class and generate any XML document without DOM.

  • The HTTP_Request package: Download this tool for GET/POST/HEAD/TRACE/PUT/DELETE, basic authentication, proxy, proxy authentication, SSL, and file uploads.

  • The OpenSSL package: Download this toolkit that implements the Secure Sockets Layer (SSL v2/v3) and Transport Layer Security (TLS v1) protocols and includes a general purpose cryptography library.

  • IBM trial software: Build your next development project with trial software available for download directly from developerWorks.

Discuss

About the author

Vikram Vaswani is the founder and CEO of Melonfire, a consulting services firm with special expertise in open-source tools and technologies. He is also the author of the books PHP Programming Solutions and How to do Everything with PHP and MySQL.

Comments (Undergoing maintenance)



Trademarks  |  My developerWorks terms and conditions

Help: Update or add to My dW interests

What's this?

This little timesaver lets you update your My developerWorks profile with just one click! The general subject of this content (AIX and UNIX, Information Management, Lotus, Rational, Tivoli, WebSphere, Java, Linux, Open source, SOA and Web services, Web development, or XML) will be added to the interests section of your profile, if it's not there already. You only need to be logged in to My developerWorks.

And what's the point of adding your interests to your profile? That's how you find other users with the same interests as yours, and see what they're reading and contributing to the community. Your interests also help us recommend relevant developerWorks content to you.

View your My developerWorks profile

Return from help

Help: Remove from My dW interests

What's this?

Removing this interest does not alter your profile, but rather removes this piece of content from a list of all content for which you've indicated interest. In a future enhancement to My developerWorks, you'll be able to see a record of that content.

View your My developerWorks profile

Return from help

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=XML, Open source
ArticleID=281708
ArticleTitle=Tip: Manipulate del.icio.us bookmarks with PHP
publish-date=01222008
author1-email=vikram.melonfire@gmail.com
author1-email-cc=dwxed@us.ibm.com

My developerWorks community

Tags

Help
Use the search field to find all types of content in My developerWorks with that tag.

Use the slider bar to see more or fewer tags.

Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere).

My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).

Use the search field to find all types of content in My developerWorks with that tag. Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere). My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).

Rate a product. Write a review.

Special offers