Use PHP with Identi.ca, Part 1

List, search, and post microblog updates to Identi.ca with PHP and the StatusNet API

Identi.ca is a popular free microblogging service that allows users to post status messages and news. Web application developers are able to create, access, and search these messages through the Identi.ca API. This two-part article introduces the Identi.ca API and illustrates how you use it with PHP to create dynamic web applications.

Vikram Vaswani, Founder, Melonfire

Photo of Vikram VaswaniVikram 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 Zend Framework: A Beginners Guide and PHP: A Beginners Guide.



16 August 2011 (First published 12 July 2011)

Also available in Chinese Japanese

16 Aug 2011 - Added sidebars with a link to Part 2 of this article in the Introduction, Thus ends Part 1, and Resources.

Introduction

Frequently used acronyms

  • API: Application programming interface
  • GNU GPL2: GNU General Public License
  • HTML: HyperText Markup Language
  • HTTP: HyperText Transfer Protocol
  • JSON: JavaScript Object Notation
  • REST: Representational State Transfer
  • RSS: Really Simple Syndication
  • URL: Uniform Resource Locator
  • XML: Extensible Markup Language

When it comes to microblogging, most people head straight for Twitter, which is today the most popular microblogging site in the world. But Twitter isn't the only game in town: Many other similar services exist, including Google Buzz, Pownce, Tumblr, Plurk, Yammer, and Identi.ca. All of these services offer similar feature sets, most notably the ability to post short status messages and receive status updates from others on the same service. In addition, many of these services offer web APIs, allowing developers to access user content through predefined APIs and use this content to create custom web applications.

In this article, I focus specifically on Identi.ca, a popular microblogging service that rivals Twitter in ease of use. Identi.ca is interesting because it runs on StatusNet, an open source PHP product that provides a complete platform for microblogging. StatusNet's open source nature means that users can download and use the platform for free, either on the public Internet or within a private network, and can also extend it with custom plug-ins and extensions.

In addition to this, StatusNet-powered sites like Identi.ca make all of their content available through a web service API, allowing application developers to search and retrieve user-created content and integrate it into custom applications. This API can return data in a variety of common formats, including XML and JSON, and can therefore be used from any programming language that supports these formats and from community-developed client libraries for PHP, Perl, and Java™ technologies.

Other articles in this series

This two-part article introduces you to the Identi.ca API, showing you how to use it to retrieve and post user status updates, access friend and follower lists, and search the network for updates matching specific search keywords. It includes examples of searching for data using various attributes and of adding, updating, and deleting data in the system.


Understanding the API

Before you can start developing applications with Identi.ca, you need to understand how the API works. As with all web services, it is necessary to first transmit an HTTP request to a designated API endpoint. This HTTP request might contain one or more input parameters for the API method, together with an identifier indicating the response format required (XML, JSON, RSS, and so on). The server responds to the query with the data set requested in the specified format; this response can then be parsed, processed, and rendered for display.

To see how this works, try to access the URL http://identi.ca/api/statuses/public_timeline.xml in your favourite web browser. This request returns a list of recently posted status messages on Identi.ca in XML format. The XML data returned by this method (which you can view in the source code of the resulting page) contains detailed information on each message and might look something like Listing 1.

Listing 1. An example API feed
<?xml version="1.0" encoding="UTF-8"?>
<statuses type="array" xmlns:statusnet="http://status.net/schema/api/1/">
 <status>
  <text>A loving postmodernist Manet-style marine cast 
    steel sculpture expressing coldness.</text>
  <truncated>false</truncated>
  <created_at>Fri Jun 24 05:43:11 +0000 2011</created_at>
  <in_reply_to_status_id></in_reply_to_status_id>
  <id>[removed]</id>
  <in_reply_to_user_id></in_reply_to_user_id>
  <in_reply_to_screen_name></in_reply_to_screen_name>
  <geo></geo>
  <favorited>false</favorited>
  <user>
   <id>[removed]</id>

   <name>Random Artwork Microblogger</name>
   <screen_name>[removed]</screen_name>
   <location>The Internet</location>
   <description>A web service generating random artwork descriptions. 
    If there is a problem with me, contact [removed].</description>
   <profile_image_url>http://avatar.identi.ca/[removed]</profile_image_url>
   <url>[removed]/</url>

   <protected>false</protected>
   <followers_count>98</followers_count>
   <profile_background_color></profile_background_color>
   <profile_text_color></profile_text_color>
   <profile_link_color></profile_link_color>
   <profile_sidebar_fill_color></profile_sidebar_fill_color>
   <profile_sidebar_border_color></profile_sidebar_border_color>
   <friends_count>1</friends_count>

   <created_at>Sun Dec 20 14:57:18 +0000 2009</created_at>
   <favourites_count>0</favourites_count>
   <utc_offset>0</utc_offset>
   <time_zone>UTC</time_zone>
   <profile_background_image_url></profile_background_image_url>
   <profile_background_tile>false</profile_background_tile>

   <statuses_count>12021</statuses_count>
   <following>false</following>
   <statusnet:blocking>false</statusnet:blocking>
   <notifications>false</notifications>
   <statusnet:profile_url>http://identi.ca/[removed]</statusnet:profile_url>
  </user>
  <statusnet:html>A loving postmodernist Manet-style marine 
    cast steel sculpture expressing coldness.</statusnet:html>
 </status>
 <status>
 ...
 </status>
</statuses>

As Listing 1 illustrates, the response to the API call is an XML-encoded list of status messages, arranged chronologically and with the most recent ones on top. This list is the so-called public timeline of Identi.ca, which you can also view on Identi.ca's home page.

The outermost <statuses> element encloses one or more <status> elements, each representing a status message posted by a user. Each entry contains various bits of information, including the text of the message, the time at which it was posted, and the location from which it was posted. A <user> subelement adds further information about the user posting the message, including the user's unique identifier, screen name, real name, profile URL, follower count, and post count.

Note these important points about the API:

  • StatusNet-powered sites like Identi.ca actually offer two different versions of the API:
    • A Twitter-compatible version that supports XML and JSON response formats
    • A StatusNet-specific REST API that returns responses in the AtomPub format

    Most of the examples in this article use the Twitter-compatible API, but I also cover a few examples of using the AtomPub-based API for completeness.

  • The API response in Listing 1 is encoded in XML, but it's just as easy to receive this response in JSON. If you look at the URL used to generate Listing 1, you see that the response format is specified at the end of the API endpoint. Obtaining a JSON response is therefore as simple as modifying the request URL to http://identi.ca/api/statuses/public_timeline.json
  • The API supports both HTTP Basic authentication and OAuth authentication. Most of the API methods used in this article series don't require authentication, but some operations, such as posting a new status message through the API, do. You'll see some examples of HTTP Basic authentication in action at various points in this article series.
  • The Identi.ca API currently doesn't include any rate limits or quotas. This limitation might change in the future, so be sure to check the latest version of the documentation when you're building your application. Remember to cache data within your application as much as possible to avoid overloading the host service.

Preparing for development

With this background information out of the way, look at integrating Identi.ca data with a PHP application. There are a couple of different ways you can do this:

  • Manually create and parse API requests and responses using such tools as the Zend Framework and PHP's XML extensions
  • Use a prebuilt PHP library such as identica-php

The first method gives you greater control over how requests are transmitted and processed, but it entails some extra effort. The second method is simpler and easier, but at the loss of some flexibility; it limits you to only those API calls that are currently supported by the library.

Some of the examples in this article series make use of Identi.ca methods that are not yet included in the identica-php library, and so the first technique is the one used in the majority of the code listings. For completeness, though, I also include some examples of using the identica-php library, to illustrate the benefits and differences.

Before you can proceed, ensure that you have the following:

  • A working Apache or PHP installation with a recent version of the Zend Framework. The Zend Framework can be downloaded as a stand-alone package; see Resources for a link to the installation guide. Not only does this library provide a solid, community-tested code base for your application, but using it also allows you to focus on core application functions, rather than on the details of navigating XML trees or handling custom namespaces.
  • A user account with identi.ca. Registration is free, and you can find a link in the Resources of this article. Make a note of your account username and password, as you'll need them when using the API. And while you're there, post a few status updates through your account as well, so that you have some basic data to play with.
  • A copy of the Twitter API documentation. No, that's not a typo: Identi.ca's API documentation for the Twitter-compatible API is still under development and so, when using the Twitter-compatible API, the best reference is probably Twitter's own API documentation. You can find links to this documentation in the Resources of this article.

Retrieving the public timeline

Assuming that you have all the necessary software, let's begin with a simple example. Listing 2 attempts to access the Identi.ca public timeline you saw in Listing 1, parse the XML response, and display it as an HTML page using PHP.

Listing 2. Retrieving the public timeline using an XML-encoded API response
<html>
  <head>
    <style>
    .item {
      float:none;
      clear:both;
      margin-top:1em; 
    } 
    </style>
  </head>
  <body>
  <?php
    // load Zend Gdata libraries
    require_once 'Zend/Loader.php';
    Zend_Loader::loadClass('Zend_Http_Client');

    // load public timeline
    try {
      $client = 
        new Zend_Http_Client('http://identi.ca/api/statuses/public_timeline.xml');
      $response = $client->request('GET');
      $xml = simplexml_load_string($response->getBody());
    } catch (Exception $e) {
      echo "Failed to read API response: " . $e->getMessage();
      exit();
    }

    // parse and display status messages
    echo '<h2>Recent public timeline updates</h2>';
    foreach ($xml->status as $entry) {        
      echo '<div class="item">';
      echo $entry->text . '<br/>';
      echo 'By: <em>' . $entry->user->name . 
        '</em> on ' . date('d M Y h:i', strtotime($entry->created_at)) . 
        '</div>';
    }
  ?>
  </body>
</html>

Listing 2 first initializes an instance of a Zend_Http_Client object, which provides an interface for sending HTTP requests and receiving the corresponding responses. The object constructor is passed the requested API endpoint, and the request() method transmits the request to the Identi.ca API. The XML response is passed through the simplexml_load_string() method, which converts it to a SimpleXML object.

You can now access individual elements of the response using standard object notation. For example, a foreach() loop iterates over the collection of <status> elements in the response, printing the text of each message, the name of the user who posted it, and the date and time of posting. Figure 1 illustrates what the result looks like (some data is redacted to protect user privacy).

Figure 1. A web page listing Identi.ca's public timeline
Screen capture of a web page listing several messages in Identi.ca's public timeline

If you'd like to use JSON results, Listing 3 illustrates how you can do this by using a .json suffix in your API request and passing the output through PHP's json_decode() function.

Listing 3. Retrieving the public timeline using a JSON-encoded API response
<html>
  <head>
    <style>
    .item {
      float:none;
      clear:both;
      margin-top:1em;
    }
    </style>
  </head>
  <body>
  <?php
    // load Zend Gdata libraries
    require_once 'Zend/Loader.php';
    Zend_Loader::loadClass('Zend_Http_Client');

    // load public timeline
    try {
      $client = 
        new Zend_Http_Client('http://identi.ca/api/statuses/public_timeline.json');
      $response = $client->request('GET');
      $json = json_decode($response->getBody());
    } catch (Exception $e) {
      echo "Failed to read API response: " . $e->getMessage();
      exit();
    }

    // parse and display status messages
    echo '<h2>Recent public timeline updates</h2>';
    foreach ($json as $entry) {        
      echo '<div class="item">';
      echo $entry->text . '<br/>';
      echo 'By: <em>' . $entry->user->name . '</em> on ' . 
        date('d M Y h:i', strtotime($entry->created_at)) . '</div>';
    }
  ?>
  </body>
</html>

Retrieving user timelines

In addition to allowing a developer to access the public timeline, the Identi.ca API also makes it possible to retrieve a list of messages posted by a specific user—the so-called user timeline. By default, the API returns the timeline for the authenticated user, but it's also possible to pass another user's screen name to the API as an optional parameter. Listing 4 illustrates the necessary code.

Listing 4. Retrieving a user timeline
<html>
  <head>
    <style>
    .item {
      float:none;
      clear:both;
      margin-top:1em;
    }
    .img {
      float:left;
      margin-right:1em; 
      padding-bottom: 10px;
      height: 48px;
      width: 48px;
    }
    </style>
  </head>
  <body>
  <?php
    // load Zend Gdata libraries
    require_once 'Zend/Loader.php';
    Zend_Loader::loadClass('Zend_Http_Client');

    // specify user credentials
    $username = 'your-username';
    $password = 'your-password';

    // load user timeline
    try {
      $client = 
        new Zend_Http_Client('http://identi.ca/api/statuses/user_timeline.xml');
      $client->setAuth($username, $password);
      $response = $client->request('GET');
      $xml = simplexml_load_string($response->getBody());
    } catch (Exception $e) {
      echo "Failed to read API response: " . $e->getMessage();
      exit();
    }

    if (count($xml->status) > 0) {
      echo '<h2>Recent status updates</h2>';
      foreach ($xml->status as $entry) {       
        echo '<div class="item"><img src="' . 
          $entry->user->profile_image_url . '" class="img" />';
        echo $entry->user->name . ' (@' . 
          $entry->user->screen_name . ')<br/>';
        $status = (trim($entry->text) != '') ? 
          $entry->text : 'No status information';
        echo '<em>' . $status . '</em></div>';      
      }
    }
  ?>
  </body>
</html>

Listing 4 is similar to Listing 2 except that it requests a different resource: the user timeline. Notice that in this case, an authenticated request is sent by using the Zend_Http_Client object's setAuth() method to set the credentials for HTTP Basic authentication. As with the public timeline, the response to this request is an XML document containing a series of status messages posted by the selected user. It's quite easy to parse and process this data with SimpleXML. Figure 2 shows an example of the output.

Figure 2. A web page listing a user's timeline
Screen capture of a web page listing a user's timeline

Listing 5 is a more interactive version of Listing 4. It contains a web form to enter an Identi.ca user name, and it retrieves the most recent messages posted by that user.

Listing 5. Retrieving a user timeline
<html>
  <head>
    <style>
    .item {
      float:none;
      clear:both;
      margin-top:1em;
    }
    .img {
      float:left;
      margin-right:1em;
      padding-bottom: 10px;
      height: 48px;
      width: 48px;
    }    
    </style>
  </head>
  <body>
    <h2>Find updates</h2>
    <form method="get">
      Get recent updates for: 
      <input type="text" name="user" />
    </form> 
    <?php
    if (isset($_GET['user'])) {
      // load Zend Gdata libraries
      require_once 'Zend/Loader.php';
      Zend_Loader::loadClass('Zend_Http_Client');

      // select user
      $user = $_GET['user'];

      // load user timeline
      try {
        $client = 
          new Zend_Http_Client('http://identi.ca/api/statuses/user_timeline.xml
          ?screen_name='.$user);
        $response = $client->request('GET');
        $xml = simplexml_load_string($response->getBody());
      } catch (Exception $e) {
        echo "Failed to read API response: " . $e->getMessage();
        exit();
      }

      if (count($xml->status) > 0) {
        echo '<h2>Recent status updates</h2>';
        foreach ($xml->status as $entry) {       
          echo '<div class="item"><img src="' . 
            $entry->user->profile_image_url . '" class="img" />';
          echo $entry->user->name . ' (@' . 
            $entry->user->screen_name . ')<br/>';
          $status = (trim($entry->text) != '') 
            ? $entry->text : 'No status information';
          echo '<em>' . $status . '</em></div>';      
        }
      }
    }
  ?>
  </body>
</html>

Figure 3 demonstrates Listing 5 in action.

Figure 3. An interactive web form to find and display a user's timeline
Screen capture of an interactive web form to find and display a user's timeline

Working with friends and followers

Like Twitter and other microblogging services, Identi.ca lets you follow other users and also allows them to follow you. The Identi.ca API includes methods to retrieve the friends and followers of a user, together with their current status. By default, the API retrieves this information for the currently authenticated user; however, it can also be used without authentication. To illustrate, consider Listing 6, which retrieves and displays the friends of the authenticated user.

Listing 6. Retrieving a user's friends
<html>
  <head>
    <style>
    .item {
      float:none;
      clear:both;
      margin-top:1em;  
    }
    .img {
      float:left;
      margin-right:1em; 
      padding-bottom: 10px;
      height: 48px;
      width: 48px;
    }
    </style>
  </head>
  <body>
  <?php
    // load Zend Gdata libraries
    require_once 'Zend/Loader.php';
    Zend_Loader::loadClass('Zend_Http_Client');

    // select user
    $username = 'your-username';
    $password = 'your-password';

    try {
      // load selected user's friends
      $client = new Zend_Http_Client('http://identi.ca/api/statuses/friends.xml');
      $client->setAuth($username, $password);
      $response = $client->request('GET');
      $friends = simplexml_load_string($response->getBody());      
    } catch (Exception $e) {
      echo "Failed to read API response: " . $e->getMessage();
      exit();
    }

    if (count((array)$friends->user) > 0) {
      echo '<h2>Friends</h2>';
      foreach ($friends->user as $user) {
          echo '<div class="item"><img src="' . 
            $user->profile_image_url . '" class="img" />';
          echo $user->name . ' (@' . $user->screen_name . ')<br/>';
          $status = (trim($user->status->text) != '') 
            ? $user->status->text : 'No status information';
          echo '<em>' . $status . '</em></div>';
      }
    }
  ?>
  </body>
</html>

In Listing 6, the XML response contains a list of entries, each representing a friend of the current user. Each user entry includes a detailed user profile, including the user's real name, screen name, profile image, location, current status, and various other attributes. This information can be extracted with SimpleXML and turned into a web page.

It's also possible to obtain this type of information for other users. Consider Listing 7, which revises Listing 6 to produce an interactive tool for friend and follower list retrieval. Simply enter a valid username and (assuming the user's privacy settings permit it) the API returns a list of friends and followers for that user.

Listing 7. Retrieving a user's friends and followers
<html>
  <head>
    <style>
    .item {
      float:none;
      clear:both;
      margin-top:1em;
    }
    .img {
      float:left;
      margin-right:1em;
      padding-bottom: 10px;
      height: 48px;
      width: 48px;
    } 
    </style>
  </head>
  <body>
    <h2>Find Friends and Followers</h2>
    <form method="get">
      Find friends and followers of: 
      <input type="text" name="user" />
    </form> 

    <?php
    if (isset($_GET['user'])) {
      // load Zend Gdata libraries
      require_once 'Zend/Loader.php';
      Zend_Loader::loadClass('Zend_Http_Client');

      // select user
      $user = $_GET['user'];

      try {
        // load selected user's friends
        $client = 
          new Zend_Http_Client('http://identi.ca/api/statuses/friends.xml
          ?screen_name=' . $user);
        $response = $client->request('GET');
        $friends = simplexml_load_string($response->getBody());

        // load selected user's followers
        $client->setUri('http://identi.ca/api/statuses/followers.xml
          ?screen_name=' . $user);
        $response = $client->request('GET');
        $followers = simplexml_load_string($response->getBody());
      } catch (Exception $e) {
        echo "Failed to read API response: " . $e->getMessage();
        exit();
      }

      if (count((array)$friends->user) > 0) {
        echo '<h2>Friends</h2>';
        foreach ($friends->user as $user) {
            echo '<div class="item"><img src="' . 
              $user->profile_image_url . '" class="img" />';
            echo $user->name . ' (@' . $user->screen_name . ')<br/>';
            $status = (trim($user->status->text) != '') 
              ? $user->status->text : 'No status information';
            echo '<em>' . $status . '</em></div>';
        }
      }

      if (count((array)$followers->user) > 0) {
        echo '<h2>Followers</h2>';
        foreach ($followers->user as $user) {
            echo '<div class="item"><img src="' . 
              $user->profile_image_url . '" class="img" />';
            echo $user->name . ' (@' . $user->screen_name . ')<br/>';
            $status = (trim($user->status->text) != '') 
              ? $user->status->text : 'No status information';
            echo '<em>' . $status . '</em></div>';
        }
      } 
    }
    ?>
  </body>
</html>

Notice that Listing 7 includes two separate API calls: The first retrieves the friend list, and the second retrieves the follower list. The data from both responses is parsed and rendered in the usual manner, with SimpleXML. Figure 4 displays an example of the output.

Figure 4. An interactive web form to find and display a user's friends and followers
Screen capture of an interactive web form to find and display a user's friends and followers

Retrieving friend timelines

You've already seen the public timeline and the user timeline, but the Identi.ca API also provides a friend's timeline. This timeline contains a combination of the messages posted by a specified user (or the currently authenticated user) and his or her friends. Consider Listing 8, which illustrates its use by requesting the friend's timeline for the currently authenticated user:

Listing 8. Retrieving a friend timeline
<html>
  <head>
    <style>
    .item {
      float:none;
      clear:both;
      margin-top:1em;  
    }
    .img {
      float:left;
      margin-right:1em; 
      padding-bottom: 10px;
      height: 48px;
      width: 48px;
    }    
    </style>
  </head>
  <body>
  <?php
    // load Zend Gdata libraries
    require_once 'Zend/Loader.php';
    Zend_Loader::loadClass('Zend_Http_Client');

    // set credentials
    $username = 'your-username';
    $password = 'your-password';

    // load friends timeline
    try {
      $client = 
        new Zend_Http_Client('http://identi.ca/api/statuses/friends_timeline.xml');
      $client->setAuth($username, $password);
      $response = $client->request('GET');
      $xml = simplexml_load_string($response->getBody());
    } catch (Exception $e) {
      echo "Failed to read API response: " . $e->getMessage();
      exit();
    }

    if (count($xml->status) > 0) {
      echo '<h2>Recent status updates</h2>';
      foreach ($xml->status as $entry) {
        echo '<div class="item"><img src="' . 
          $entry->user->profile_image_url . '" class="img" />';
        echo $entry->user->name . ' (@' . 
          $entry->user->screen_name . ')<br/>';
        $status = (trim($entry->text) != '') 
          ? $entry->text : 'No status information';
        echo '<em>' . $status . '</em></div>'; 
      }
    }
  ?>
  </body>
</html>

Using the alternative AtomPub API

The previous examples have all made use of Identi.ca's Twitter-compatible API. As discussed at the beginning of this article, however, Identi.ca also has another version of the API available, which produces results in AtomPub format. Although this API doesn't include all the functionality of the Twitter-compatible API, it produces richer data and might be a useful alternative in some use cases.

To illustrate how the AtomPub API works, Listing 9 replicates Listing 2 and uses the AtomPub API to build a representation of the public timeline.

Listing 9. Retrieving the public timeline using the AtomPub API
<html>
  <head>
    <style>
    .item {
      float:none;
      clear:both;
      margin-top:1em; 
    }
    </style>
  </head>
  <body>
  <?php
    // load Zend Gdata libraries
    require_once 'Zend/Loader.php';
    Zend_Loader::loadClass('Zend_Feed');

    // load public timeline
    try {
      $feed = Zend_Feed::import('http://identi.ca/api/statuses/public_timeline.atom');
    } catch (Zend_Feed_Exception $e) {
      echo "Failed to import feed: " . $e->getMessage();
      exit();
    }

    echo '<h2>Recent public timeline updates</h2>';
    foreach ($feed as $entry) {
      echo '<div class="item">';
      echo $entry->title . '<br/>';
      echo 'By: <em>' . $entry->author->name . '</em> on ' . 
        date('d M Y h:i', strtotime($entry->published)) . '</div>';
    }
  ?>
  </body>
</html>

Notice from Listing 9 that the endpoint for the AtomPub API is almost the same (in this case) as the endpoint for the Twitter-compatible API, the only difference being the use of the .atom suffix. The response to this API request is an Atom feed containing the latest posts from Identi.ca, as in Figure 5.

Figure 5. An example AtomPub feed
Screen capture of an example AtomPub feed with several identi.ca messages

Although it's certainly possible to process this feed with SimpleXML, as was done earlier in Listing 2, the Zend Framework offers a better option in the form of its Zend_Feed component, which is specifically designed to parse Atom and RSS feeds. The Zend_Feed import() method is used to import the Atom feed and turn it into an object, which can then be processed using standard object-property notation. As before, the script iterates over the entries in the feed, extracting each entry's title, author, and publication date, to produce output like that in Figure 1.


Using alternative PHP libraries

If you don't like the idea of rolling your own code with tools like SimpleXML and the Zend Framework, you can use ready-made libraries to interact with the Identi.ca API from PHP. One library is identica-php, which provides a full-featured implementation of Identi.ca's Twitter-compatible API and has the added benefit of being extremely easy to understand and simple to use. It is distributed under the GNU GPL2, and it can be freely downloaded and used in any PHP environment that includes cURL support. You can find a link to download it in Resources, together with a pointer to the PHP manual page that explains how to activate cURL support.

To see how identica-php works, consider Listing 10, which uses it to retrieve Identi.ca's public timeline.

Listing 10. Retrieving the public timeline using the identica-php library
<html>
  <head>
    <style>
    .item {
      float:none;
      clear:both;
      margin-top:1em;
    }  
    </style>
  </head>
  <body>
  <?php
  // load required library file
  require_once('identica.lib.php');

  // initialize service object
  $service = new Identica(false, false);

  // get public timeline
  $xml = simplexml_load_string($service->getPublicTimeline('xml'));
  
  // process and display entries
  echo '<h2>Recent public timeline updates</h2>';
  foreach ($xml->status as $entry) {
    echo '<div class="item">';
    echo $entry->text . '<br/>';
    echo 'By: <em>' . $entry->user->screen_name . '</em> on ' . 
      date('d M Y h:i', strtotime($entry->created_at)) . '</div>';  
  }
  ?>
  </body>
</html>

Listing 10 first loads the identica-php class libraries and initializes a new instance of the Identi.ca service object. Typically, this object is initialized with a valid Identi.ca username and password; in this listing, these credentials are omitted as the resource being accessed is a public resource.

The service object exposes a number of different methods that map directly to methods in the Twitter-compatible API. Listing 10 uses one of these methods, getPublicTimeline(), to retrieve the current public timeline from Identi.ca. This method accepts one additional parameter, which specifies the format in which data should be returned—in this case, XML—and once invoked, internally use cURL to transmit the request and retrieve the response.

Once received, the response is passed through PHP's simplexml_load_string() function to convert it into a SimpleXML object, and the various bits of data required to construct the page are extracted as before using SimpleXML notation. The output in this case is equivalent to that in Figure 1.

Listing 11 offers another example of how the identica-php library can simplify some operations, by rewriting Listing 7 to use it when retrieving a user's friends and followers.

Listing 11. Retrieving a user's friends and followers using the identica-php library
<html>
  <head>
    <style>
    .item {
      float:none;
      clear:both;
      margin-top:1em;
    }
    .img {
      float:left;
      margin-right:1em;
      padding-bottom: 10px;
      height: 48px;
      width: 48px;
    } 
    </style>
  </head>
  <body>
    <h2>Find Friends and Followers</h2>
    <form method="get">
      Find friends and followers of: 
      <input type="text" name="user" />
    </form> 

    <?php
    if (isset($_GET['user'])) {
      // load required library file
      require_once('identica.lib.php');

      // set credentials
      $username = 'your-username';
      $password = 'your-password';

      // initialize service object
      $service = new Identica($username, $password);

      // select user
      $user = $_GET['user'];

      // get user's friends
      $friends = simplexml_load_string($service->getFriends('xml', $user));

      // get user's followers
      $followers = simplexml_load_string($service->getFollowers('xml', $user));

      if (count((array)$friends->user) > 0) {
        echo '<h2>Friends</h2>';
        foreach ($friends->user as $user) {
            echo '<div class="item"><img src="' . 
              $user->profile_image_url . '" class="img" />';
            echo $user->name . ' (@' . $user->screen_name . ')<br/>';
            $status = (trim($user->status->text) != '') 
              ? $user->status->text : 'No status information';
            echo '<em>' . $status . '</em></div>';
        }
      } 

      if (count((array)$followers->user) > 0) {
        echo '<h2>Followers</h2>';
        foreach ($followers->user as $user) {
            echo '<div class="item"><img src="' . 
              $user->profile_image_url . '" class="img" />';
            echo $user->name . ' (@' . $user->screen_name . ')<br/>';
            $status = (trim($user->status->text) != '') 
              ? $user->status->text : 'No status information';
            echo '<em>' . $status . '</em></div>';
        }
      }

    }
    ?>
  </body>
</html>

Most of the heavy lifting in this case is done by the getFriends() and getFollowers() methods, which accept a user name and format specifier and take care of formulating the corresponding URL, sending the request, and receiving the response. The output in this case is the same as that in Figure 4.


Thus ends Part 1

Other articles in this series

What you've seen so far is just the tip of the iceberg. The examples in this article focused only on reading data from the Identi.ca API. If you build a real-world application, chances are that you'll also need to write data back to Identi.ca using the API—for example, to post status updates or set up follower/friend relationships. A number of methods allow you to perform these operations, and they are discussed in detail in the second part of this article.

Resources

Learn

Get products and technologies

Discuss

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into XML on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=XML, Open source
ArticleID=711062
ArticleTitle=Use PHP with Identi.ca, Part 1
publish-date=08162011