Manipulate del.icio.us bookmarks with PHP

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.

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
?>?>?>?>




...




Figure 1 shows this output in Mozilla Firefox:

Figure 1. 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
?>?>?>?>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



My Bookmarks


?>?>?>?>getRecentPosts();
echo "
    \n";
    foreach ($posts as $p) {
    echo "
  • \n";
    echo " " . $p['description'] . "
    \n";
    echo " " . implode(' ', $p['tag']) . "\n";
    echo "
  • \n";
    }
    echo "
\n";
?>





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

Back to top





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



My Tags


?>?>?>?>getTags();
echo "\n";
foreach ($tags as $tag => $count) {
echo " \n";
echo " \n";
echo " \n";
echo " \n";
}
echo "
$tag$count
\n";
?>





And Figure 3 illustrates what the output might look like:

Figure 3. 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



My Bookmarks


?>?>?>?>getPosts(array('book'));
echo "
    \n";
    foreach ($posts as $p) {
    echo "
  • \n";
    echo " " . $p['description'] . "
    \n";
    echo " " . implode(' ', $p['tag']) . "\n";
    echo "
  • \n";
    }
    echo "
\n";
?>





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

Back to top





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
?>?>?>?>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
?>?>?>?>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!

Back to top





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



My Bookmarks


?>?>?>?>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 "
    \n";
    foreach ($posts as $p) {
    echo "
  • \n";
    echo "" . $p['description'] . "
    \n";
    echo "" . implode(' ', $p['tag']) . "\n";
    echo "
  • \n";
    }
    echo "
\n";
?>

Add New Bookmark


">
URL *:


Description *:


Tags:









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

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
Share this...
Digg this story
Post to del.icio.us
Slashdot it!




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!

Komentar