While tweaking the PageCookery theme a few days ago, I wanted to display the books and movies I had recently marked on Douban. At first I just typed them in by hand. That was manageable for books, since I rarely finish more than one in a year, but movies pile up much faster, and manually maintaining the list clearly wasn’t practical.

So I started looking into the Douban API. It turned out that Douban provides both Atom and JSON output. I used the Atom version here. If you specifically want JSON, you’ll need to look that up separately.

The implementation is straightforward. I wrapped it in a function called Douban:

<?php
function Douban($username, $subject, $apikey)
{
if ($apikey == "")
{
  $apikey='064e10081295144112ea301837bf3cc3';
}
$douban='http://api.douban.com/people/' . $username . '/collection?cat=' . $subject . '&apikey=' . $apikey ;
$feed =  simplexml_load_file($douban);
$children =  $feed->children('http://www.w3.org/2005/Atom');
$a = $children-> entry->children('http://www.w3.org/2005/Atom')->xpath('//db:subject');
echo '<ul>';
foreach ($a as $d) echo '<li>' . $d -> title . '</li>';
echo '</ul>';
}

I defined it as a function so it could be dropped into a theme easily. In WordPress, that would go into function.php. For PageCookery, I placed it in /lib/function_microblog.php. For anything else, just put it wherever it makes sense in your setup.

When calling it, the format is simple:

<?php Douban('lizheming', 'movie' , '');//形式是昵称|收藏类型|API_KEY ?>

The three supported collection types are movie, book, and music.

I set the function so that if API_KEY is left empty, it falls back to a default key. Even so, it’s still better to apply for your own. Douban’s API has request rate limits, and if too many people share the same key at the same time, problems can show up.

If you’re working with the Atom feed in PHP and want to understand the XML handling part more clearly, SimpleXML is worth reading up on. It makes parsing this kind of feed much easier.