Use PHP with Identi.ca, Part 2 - grch.com.ar · Use PHP with Identi.ca, Part 2 List, search, and...

24
Use PHP with Identi.ca, Part 2 List, search, and post microblog updates to Identi.ca with PHP and the StatusNet API Skill Level: Intermediate Vikram Vaswani Founder Melonfire 16 Aug 2011 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. Introduction Other articles in this series Use PHP with Identi.ca, Part 1 In the first part of this article, I introduced you to the Identi.ca web service API and showed you a few examples of using the API to read and use data from Identi.ca in a PHP-based web application. In that article, I also introduced you to the two flavors of the Identi.ca API and illustrated how you can use the Identi.ca API either by writing your own code with tools such as SimpleXML and the Zend Framework or by using a ready-made PHP library such as identica-php. All the examples in the previous article focused on read-only access to the API. In this concluding article, I show you how to take a user's input and feed it back to Identi.ca through the API. With this approach, you improve functionality in your PHP Use PHP with Identi.ca, Part 2 Trademarks © Copyright IBM Corporation 2011 Page 1 of 24

Transcript of Use PHP with Identi.ca, Part 2 - grch.com.ar · Use PHP with Identi.ca, Part 2 List, search, and...

Page 1: Use PHP with Identi.ca, Part 2 - grch.com.ar · Use PHP with Identi.ca, Part 2 List, search, and post microblog updates to Identi.ca with PHP and the StatusNet API Skill Level: Intermediate

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

Skill Level: Intermediate

Vikram VaswaniFounderMelonfire

16 Aug 2011

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

Introduction

Other articles in this series

• Use PHP with Identi.ca, Part 1

In the first part of this article, I introduced you to the Identi.ca web service API andshowed you a few examples of using the API to read and use data from Identi.ca ina PHP-based web application. In that article, I also introduced you to the two flavorsof the Identi.ca API and illustrated how you can use the Identi.ca API either bywriting your own code with tools such as SimpleXML and the Zend Framework or byusing a ready-made PHP library such as identica-php.

All the examples in the previous article focused on read-only access to the API. Inthis concluding article, I show you how to take a user's input and feed it back toIdenti.ca through the API. With this approach, you improve functionality in your PHP

Use PHP with Identi.ca, Part 2 Trademarks© Copyright IBM Corporation 2011 Page 1 of 24

Page 2: Use PHP with Identi.ca, Part 2 - grch.com.ar · Use PHP with Identi.ca, Part 2 List, search, and post microblog updates to Identi.ca with PHP and the StatusNet API Skill Level: Intermediate

scripts as you include capabilities to create new posts, mark posts as favorites, andset up follower relationships. So let's get going!

Searching status notices

Frequently used acronyms

• API: Application programming interface

• HTTP: HyperText Transfer Protocol

• JSON: JavaScript Object Notation

• RSS: Really Simple Syndication

• URL: Uniform Resource Locator

• XML: Extensible Markup Language

Search is one of the most common reasons to use the API. Like the Twitter API (onwhich it is based), the Identi.ca API exposes a search interface that returns results inboth Atom and JSON formats. This search interface is accessible at the URLhttp://identi.ca/api/search.atom and is most easily processed with a tool like theZend_Feed component, which you saw in Part 1 of this article.

Listing 1 illustrates how to search Identi.ca for posts matching a specific query termand display them using Zend_Feed.

Listing 1. Searching Identi.ca

<?php// load Zend Gdata librariesrequire_once 'Zend/Loader.php';Zend_Loader::loadClass('Zend_Feed');

// define query term$q = 'green lantern';

// load search resultstry {$feed = Zend_Feed::import('http://identi.ca/api/search.atom?q=' . urlencode($q));

} catch (Zend_Feed_Exception $e) {echo "Failed to import feed: " . $e->getMessage();exit();

}

if ($feed->count() > 0) {echo "<h2>Search results for '$q'</h2>";foreach ($feed as $entry) {

echo '<div>';echo $entry->title . '<br/>';echo 'By: <em>' . $entry->author->name .'</em> on ' . date('d M Y h:i', strtotime($entry->published)) .'</div> <br/>';

}}

developerWorks® ibm.com/developerWorks

Use PHP with Identi.ca, Part 2 Trademarks© Copyright IBM Corporation 2011 Page 2 of 24

Page 3: Use PHP with Identi.ca, Part 2 - grch.com.ar · Use PHP with Identi.ca, Part 2 List, search, and post microblog updates to Identi.ca with PHP and the StatusNet API Skill Level: Intermediate

?>

As Listing 1 illustrates, an Identi.ca search is performed by appending the queryterm to the request URL using the q parameter. Because the request URL has a.atom suffix, the search results are returned as an Atom feed, suitable forconsumption by the Zend_Feed component, which is specifically designed to parseAtom and RSS feeds.

The Zend_Feed import() method is used to import the Atom feed and turn it into anobject, which can then be processed using standard object-property notation. Listing1 illustrates how to use Zend_Feed to iterate over the entries in the feed, extractingeach entry's title, author, and publication date, to produce output like that shown inFigure 1.

Figure 1. A web page listing search results

ibm.com/developerWorks developerWorks®

Use PHP with Identi.ca, Part 2 Trademarks© Copyright IBM Corporation 2011 Page 3 of 24

Page 4: Use PHP with Identi.ca, Part 2 - grch.com.ar · Use PHP with Identi.ca, Part 2 List, search, and post microblog updates to Identi.ca with PHP and the StatusNet API Skill Level: Intermediate

Example application: Interactive search utility

Listing 2 revises Listing 1 to create a more interactive search utility, allowing the userto enter a search term into a form and view Identi.ca posts matching the searchterm.

Listing 2. An interactive Identi.ca search utility

<html><head>

<style>.item {

developerWorks® ibm.com/developerWorks

Use PHP with Identi.ca, Part 2 Trademarks© Copyright IBM Corporation 2011 Page 4 of 24

Page 5: Use PHP with Identi.ca, Part 2 - grch.com.ar · Use PHP with Identi.ca, Part 2 List, search, and post microblog updates to Identi.ca with PHP and the StatusNet API Skill Level: Intermediate

float:none;clear:both;margin-top:1em;

}</style>

</head><body>

<h2>Search </h2><form method="get">Search for: <input type="text" name="q" /></form><?phpif (isset($_GET['q'])) {// load Zend Gdata librariesrequire_once 'Zend/Loader.php';Zend_Loader::loadClass('Zend_Feed');

// define query term$q = urlencode($_GET['q']);

// load search resultstry {

$feed = Zend_Feed::import('http://identi.ca/api/search.atom?rpp=25&q=' . $q);

} catch (Zend_Feed_Exception $e) {echo "Failed to import feed: " . $e->getMessage();exit();

}

if ($feed->count() > 0) {echo "<h2>Search results for '$q'</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>

Listing 2 is a minor revision of Listing 1, adding support for passes, which the inputprovided, by the user to the search request URL endpoint; it parses the resultingAtom feed to produce a list of matching search results. The additional rppparameter in the request URL specifies the number of results per page. Note thatthe query term must be URL-encoded before it passes to the API.

Figure 2 illustrates the tool in action.

Figure 2. An interactive Identi.ca search engine

ibm.com/developerWorks developerWorks®

Use PHP with Identi.ca, Part 2 Trademarks© Copyright IBM Corporation 2011 Page 5 of 24

Page 6: Use PHP with Identi.ca, Part 2 - grch.com.ar · Use PHP with Identi.ca, Part 2 List, search, and post microblog updates to Identi.ca with PHP and the StatusNet API Skill Level: Intermediate

Adding and deleting status notices

Just as you can search posts, so too can you create them afresh. The Identi.ca APIincludes methods to post new status messages or remove existing ones. To post anew message to a user's timeline, an authenticated client must transmit the requestusing POST. The Zend_Http_Client component, which you've also previously met inPart 1, supports both POST and authentication and therefore fits the need well.

Take a look at Listing 3, which illustrates the process of posting a new statusmessage to the user timeline through the API.

Listing 3. Posting a new status message

developerWorks® ibm.com/developerWorks

Use PHP with Identi.ca, Part 2 Trademarks© Copyright IBM Corporation 2011 Page 6 of 24

Page 7: Use PHP with Identi.ca, Part 2 - grch.com.ar · Use PHP with Identi.ca, Part 2 List, search, and post microblog updates to Identi.ca with PHP and the StatusNet API Skill Level: Intermediate

<?php// load Zend Gdata librariesrequire_once 'Zend/Loader.php';Zend_Loader::loadClass('Zend_Http_Client');

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

// post notice and display unique identifier// if message successfully postedtry {$client = new Zend_Http_Client('http://identi.ca/api/statuses/update.xml');$client->setAuth($username, $password);$client->setParameterPost('status', 'Happy hippos in the sun');$response = $client->request('POST');$xml = simplexml_load_string($response->getBody());if ($xml->id) {

echo 'New notice created with id: ' . $xml->id;} else {

if ($xml->error) {throw new Exception($xml->error);

} else {throw new Exception('Unspecified error');

}}

} catch (Exception $e) {echo "ERROR: " . $e->getMessage();exit();

}?>

Listing 3 begins by loading the necessary class libraries and defining the user'saccount credentials. A Zend_Http_Client object is initialized with the API endpointURL, and the setAuth() method is used to set account credentials for authentication.The status message text is then added to the request as a POST parameter usingthe "status" request argument, and the entire request is transmitted to Identi.ca.

If successful, Identi.ca returns an XML response representing the newly createdmessage, together with its unique identifier. It's possible to then parse this XMLdocument and display a message indicating success or failure. The newly createdmessage also appears in the user's timeline on Identi.ca.

Removing an existing message is equally simple; all you need is the message'sunique identifier, which should be POST-ed to the API endpoint for messagedeletion. Listing 4 illustrates the process.

Listing 4. Deleting a status message

<?php// load Zend Gdata librariesrequire_once 'Zend/Loader.php';Zend_Loader::loadClass('Zend_Http_Client');

// define user credentials$username = 'your-username';

ibm.com/developerWorks developerWorks®

Use PHP with Identi.ca, Part 2 Trademarks© Copyright IBM Corporation 2011 Page 7 of 24

Page 8: Use PHP with Identi.ca, Part 2 - grch.com.ar · Use PHP with Identi.ca, Part 2 List, search, and post microblog updates to Identi.ca with PHP and the StatusNet API Skill Level: Intermediate

$password = 'your-password';

// define ID of notice to delete$id = '0011223344';

// delete specified noticetry {$client = new Zend_Http_Client(

"http://identi.ca/api/statuses/destroy/$id.xml");$client->setAuth($username, $password);$response = $client->request('POST');$xml = simplexml_load_string($response->getBody());if ($xml->id) {

echo 'Notice with id: ' . $xml->id . ' successfully deleted.';} else {

if ($xml->error) {throw new Exception($xml->error);

} else {throw new Exception('Unspecified error');

}}

} catch (Exception $e) {echo "Failed to read API response: " . $e->getMessage();exit();

}?>

Example application: User timeline editor

It's quite easy to apply the techniques shown in Listing 3 and Listing 4 to create aninteractive view of a user's timeline. This view allows the user to see his or herprevious messages, and it provides controls to delete existing messages or add newones.

Listing 5 displays the complete code.

Listing 5. User timeline editor

<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 librariesrequire_once 'Zend/Loader.php';Zend_Loader::loadClass('Zend_Http_Client');

developerWorks® ibm.com/developerWorks

Use PHP with Identi.ca, Part 2 Trademarks© Copyright IBM Corporation 2011 Page 8 of 24

Page 9: Use PHP with Identi.ca, Part 2 - grch.com.ar · Use PHP with Identi.ca, Part 2 List, search, and post microblog updates to Identi.ca with PHP and the StatusNet API Skill Level: Intermediate

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

// set up authenticated client$client = new Zend_Http_Client();$client->setAuth($username, $password);

try {// post message if message text presentif (isset($_POST['m'])) {

$client->setUri('http://identi.ca/api/statuses/update.xml');$client->setParameterPost('status', $_POST['m']);$response = $client->request('POST');$xml = simplexml_load_string($response->getBody());if (!isset($xml->id)) {if ($xml->error) {

throw new Exception($xml->error);} else {

throw new Exception('Unspecified error');}

}// delete message if message id present} else if (isset($_GET['d'])) {

$id = $_GET['d'];$client->setUri('http://identi.ca/api/statuses/destroy/$id.xml');

$response = $client->request('POST');$xml = simplexml_load_string($response->getBody());if (!isset($xml->id)) {if ($xml->error) {

throw new Exception($xml->error);} else {

throw new Exception('Unspecified error');}

}}

// load user timeline$client->setUri(

'http://identi.ca/api/statuses/user_timeline.xml');$response = $client->request('GET');$xml = simplexml_load_string($response->getBody());

} catch (Exception $e) {echo "ERROR: " . $e->getMessage();exit();

}

// parse and display status messagesif (count($xml->status) > 0) {echo '<h2>Recent status 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)) .'<br/>';

echo '<small>';echo '<a href="?d=' . $entry->id . '">Delete</a>';echo '</small>';echo '</div>';

}}?>

<h2>Add New Post</h2><form method="post">

ibm.com/developerWorks developerWorks®

Use PHP with Identi.ca, Part 2 Trademarks© Copyright IBM Corporation 2011 Page 9 of 24

Page 10: Use PHP with Identi.ca, Part 2 - grch.com.ar · Use PHP with Identi.ca, Part 2 List, search, and post microblog updates to Identi.ca with PHP and the StatusNet API Skill Level: Intermediate

Message: <input type="text" name="m" /> <br/><input type="submit" name="submit" value="Post" />

</form></body>

</html>

This code might seem complex at first glance, but it's actually quite simple. Listing 5first loads the Zend Framework class libraries and sets up an authenticated HTTPclient. It also retrieves the current user timeline, using a technique discussed in Part1, and parses the timeline XML to display a list of the user's previous messages.Each message is accompanied with a "Delete" link, which also includes themessage's unique identifier as a GET variable. The code also includes a simple webform for the user to enter a new status message; on submission, the message istransmitted to the form processing script using POST.

Each time the script is requested, it checks to see whether the request method isGET or POST and uses this distinction to decide the action to take:

• For POST requests, the script retrieves the message entered by the userand then POSTs it to the API endpoint for new message creation, asshown in Listing 3.

• For GET requests, the script retrieves the message identifier included inthe request URL and then POSTs it to the API endpoint for messagedeletion, as shown in Listing 4.

Figure 3 shows the script in action, displaying a list of the user's recent messages.

Figure 3. A web page listing the current user timeline

developerWorks® ibm.com/developerWorks

Use PHP with Identi.ca, Part 2 Trademarks© Copyright IBM Corporation 2011 Page 10 of 24

Page 11: Use PHP with Identi.ca, Part 2 - grch.com.ar · Use PHP with Identi.ca, Part 2 List, search, and post microblog updates to Identi.ca with PHP and the StatusNet API Skill Level: Intermediate

Figure 4 displays the result of adding a new post through the web form.

Figure 4. A web page listing the updated user timeline after posting a message

ibm.com/developerWorks developerWorks®

Use PHP with Identi.ca, Part 2 Trademarks© Copyright IBM Corporation 2011 Page 11 of 24

Page 12: Use PHP with Identi.ca, Part 2 - grch.com.ar · Use PHP with Identi.ca, Part 2 List, search, and post microblog updates to Identi.ca with PHP and the StatusNet API Skill Level: Intermediate

Managing user subscriptions

In addition to posting and removing messages to your own timeline through the API,you can also manage follower relationships through the API. The API includesmethods to list the users following, and being followed by, the authenticated userand also includes the ability to add or remove users from the follower list.

To see this in action, consider Listing 6, which illustrates how to follow anotherIdenti.ca user.

developerWorks® ibm.com/developerWorks

Use PHP with Identi.ca, Part 2 Trademarks© Copyright IBM Corporation 2011 Page 12 of 24

Page 13: Use PHP with Identi.ca, Part 2 - grch.com.ar · Use PHP with Identi.ca, Part 2 List, search, and post microblog updates to Identi.ca with PHP and the StatusNet API Skill Level: Intermediate

Listing 6. Creating a follower relationship

<?php// load Zend Gdata librariesrequire_once 'Zend/Loader.php';Zend_Loader::loadClass('Zend_Http_Client');

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

// define user to follow$u = 'some-user';

// follow a usertry {$client = new Zend_Http_Client(

'http://identi.ca/api/friendships/create.xml');$client->setAuth($username, $password);$client->setParameterPost('screen_name', $u);$response = $client->request('POST');$xml = @simplexml_load_string($response->getBody());if ($xml->following == 'true') {

echo 'Now following user: ' . $u;} else {

if ($xml->error) {throw new Exception($xml->error);

} else {throw new Exception('Unspecified error');

}}

} catch (Exception $e) {echo "Failed to read API response: " . $e->getMessage();exit();

}?>

As Listing 6 illustrates, a POST request must be transmitted to the API endpoint byan authenticated client with the screen name of the user to be followed. Ifsuccessful, the response contains an XML document with details of the specifieduser, with the special following property set true.

Listing 7 illustrates the process of unfollowing (that is, breaking a followerrelationship).

Listing 7. Breaking a follower relationship

<?php// load Zend Gdata librariesrequire_once 'Zend/Loader.php';Zend_Loader::loadClass('Zend_Http_Client');

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

// define user to unfollow$u = 'some-user';

// unfollow a user

ibm.com/developerWorks developerWorks®

Use PHP with Identi.ca, Part 2 Trademarks© Copyright IBM Corporation 2011 Page 13 of 24

Page 14: Use PHP with Identi.ca, Part 2 - grch.com.ar · Use PHP with Identi.ca, Part 2 List, search, and post microblog updates to Identi.ca with PHP and the StatusNet API Skill Level: Intermediate

try {$client = new Zend_Http_Client(

'http://identi.ca/api/friendships/destroy.xml');$client->setAuth($username, $password);$client->setParameterPost('screen_name', $u);$response = $client->request('POST');$xml = @simplexml_load_string($response->getBody());if ($xml->following == 'false') {

echo 'No longer following user: ' . $u;} else {

if ($xml[0]) {throw new Exception($xml[0]);

} else {throw new Exception('Unspecified error');

}}

} catch (Exception $e) {echo "Failed to read API response: " . $e->getMessage();exit();

}?>

Managing user favorites

Identi.ca, like Twitter, allows users to mark certain messages as favorites. Thisability is a convenient way for users to flag certain messages as particularlyinteresting and valuable. The Identi.ca API includes methods to retrieve a user'sfavorites, as well as add and delete items to and from the list.

Listing 8 provides an example of retrieving all the authenticated user's favoritemessages.

Listing 8. Retrieving user favorites

<html><head>

<style>.item {float:none;clear:both;margin-top:1em;

}</style>

</head><body><?php// load Zend Gdata librariesrequire_once 'Zend/Loader.php';Zend_Loader::loadClass('Zend_Http_Client');

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

// list user favoritestry {

$client = new Zend_Http_Client('http://identi.ca/api/favorites.xml');$client->setAuth($username, $password);$response = $client->request('GET');

developerWorks® ibm.com/developerWorks

Use PHP with Identi.ca, Part 2 Trademarks© Copyright IBM Corporation 2011 Page 14 of 24

Page 15: Use PHP with Identi.ca, Part 2 - grch.com.ar · Use PHP with Identi.ca, Part 2 List, search, and post microblog updates to Identi.ca with PHP and the StatusNet API Skill Level: Intermediate

$xml = simplexml_load_string($response->getBody());} catch (Exception $e) {

echo "Failed to read API response: " . $e->getMessage();exit();

}

// parse and display favorite status messagesecho '<h2>Favorites</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>

Retrieving favorites is quite simple: Send a GET request to the favorites endpoint,and the response is an XML document containing a list of the user's favoritemessages. Figure 5 displays an example of the output.

Figure 5. A web page listing user favorites

Note that it's also possible to retrieve another user's favorites simply by passing thetarget user's screen name to the endpoint using the id parameter.

To programmatically add a new message to a user's favorites, it's necessary to firstobtain the message's unique identifier. Assuming that you have this, you can send aPOST request to the API referencing the id, as in Listing 9.

Listing 9. Adding a favorite message

ibm.com/developerWorks developerWorks®

Use PHP with Identi.ca, Part 2 Trademarks© Copyright IBM Corporation 2011 Page 15 of 24

Page 16: Use PHP with Identi.ca, Part 2 - grch.com.ar · Use PHP with Identi.ca, Part 2 List, search, and post microblog updates to Identi.ca with PHP and the StatusNet API Skill Level: Intermediate

<?php// load Zend Gdata librariesrequire_once 'Zend/Loader.php';Zend_Loader::loadClass('Zend_Http_Client');

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

// define ID of notice to be favored$id = '0011223344';

// favor a noticetry {$client = new Zend_Http_Client(

"http://identi.ca/api/favorites/create/$id.xml");$client->setAuth($username, $password);$response = $client->request('POST');$xml = simplexml_load_string($response->getBody());if ($xml->favorited == 'true') {

echo 'Successfully added favorite.';} else {

if ($xml->error) {throw new Exception($xml->error);

} else {throw new Exception('Unspecified error');

}}

} catch (Exception $e) {echo "ERROR: " . $e->getMessage();exit();

}?>

The response to a successful POST is an XML document containing the messagemetadata and content, with the favorited property set to true.

As you might have guessed by now, it's also possible to programmatically remove afavorite message, again by passing the message identifier to the correct APIendpoint. Listing 10 illustrates the code.

Listing 10. Deleting a favorite message

<?php// load Zend Gdata librariesrequire_once 'Zend/Loader.php';Zend_Loader::loadClass('Zend_Http_Client');

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

// define ID of notice to be disfavored$id = '0011223344';

// disfavor a noticetry {$client = new Zend_Http_Client(

"http://identi.ca/api/favorites/destroy/$id.xml");$client->setAuth($username, $password);

developerWorks® ibm.com/developerWorks

Use PHP with Identi.ca, Part 2 Trademarks© Copyright IBM Corporation 2011 Page 16 of 24

Page 17: Use PHP with Identi.ca, Part 2 - grch.com.ar · Use PHP with Identi.ca, Part 2 List, search, and post microblog updates to Identi.ca with PHP and the StatusNet API Skill Level: Intermediate

$response = $client->request('POST');$xml = simplexml_load_string($response->getBody());if ($xml->favorited == 'false') {

echo 'Successfully removed favorite.';} else {

if ($xml->error) {throw new Exception($xml->error);

} else {throw new Exception('Unspecified error');

}}

} catch (Exception $e) {echo "ERROR: " . $e->getMessage();exit();

}?>

Example application: dashboard

With all this information at hand, you can now build a simple browser-basedmanagement interface to Identi.ca, one that's similar to what appears on theIdenti.ca home page. This interface displays the current public timeline and offersfunctions to follow other users or mark certain messages as favorites.

Listing 11 has the complete code.

Listing 11. The Identi.ca dashboard

<html><head>

<style>.item {float:none;clear:both;margin-top:1em;

}</style>

</head><body>

<?php// load Zend Gdata librariesrequire_once 'Zend/Loader.php';Zend_Loader::loadClass('Zend_Http_Client');

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

$client = new Zend_Http_Client();$client->setAuth($username, $password);

try {if (isset($_GET['o'])) {

switch ($_GET['o']) {case 'follow':

$client->setUri('http://identi.ca/api/friendships/create.xml');$client->setParameterPost('user_id', $_GET['d']);$response = $client->request('POST');$xml = @simplexml_load_string($response->getBody());if ($xml->following != 'true') {

ibm.com/developerWorks developerWorks®

Use PHP with Identi.ca, Part 2 Trademarks© Copyright IBM Corporation 2011 Page 17 of 24

Page 18: Use PHP with Identi.ca, Part 2 - grch.com.ar · Use PHP with Identi.ca, Part 2 List, search, and post microblog updates to Identi.ca with PHP and the StatusNet API Skill Level: Intermediate

if ($xml->error) {throw new Exception($xml->error);

} else {throw new Exception('Unspecified error');

}}break;

case 'unfollow':$client->setUri('http://identi.ca/api/friendships/destroy.xml');$client->setParameterPost('user_id', $_GET['d']);$response = $client->request('POST');$xml = @simplexml_load_string($response->getBody());if ($xml->following != 'false') {

if ($xml->error) {throw new Exception($xml->error);

} else {throw new Exception('Unspecified error');

}}break;

case 'favor':$client->setUri(

'http://identi.ca/api/favorites/create/' . $_GET['d'] . '.xml');$response = $client->request('POST');$xml = simplexml_load_string($response->getBody());if ($xml->favorited != 'true') {

if ($xml->error) {throw new Exception($xml->error);

} else {throw new Exception('Unspecified error');

}}break;

case 'disfavor':$client->setUri(

'http://identi.ca/api/favorites/destroy/' . $_GET['d'] . '.xml');$response = $client->request('POST');$xml = simplexml_load_string($response->getBody());if ($xml->favorited != 'false') {

if ($xml->error) {throw new Exception($xml->error);

} else {throw new Exception('Unspecified error');

}}break;

}}

// load public timeline$client->setUri(

'http://identi.ca/api/statuses/public_timeline.xml');$response = $client->request('GET');$xml = simplexml_load_string($response->getBody());

} catch (Exception $e) {echo "ERROR: " . $e->getMessage();exit();

}

// parse and display status messagesecho '<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 ' .

developerWorks® ibm.com/developerWorks

Use PHP with Identi.ca, Part 2 Trademarks© Copyright IBM Corporation 2011 Page 18 of 24

Page 19: Use PHP with Identi.ca, Part 2 - grch.com.ar · Use PHP with Identi.ca, Part 2 List, search, and post microblog updates to Identi.ca with PHP and the StatusNet API Skill Level: Intermediate

date('d M Y h:i', strtotime($entry->created_at)) .'<br/>';

echo '<small>';echo ($entry->user->following == 'false') ?

'<a href="?o=follow&d=' . $entry->user->id .'">Follow user</a>' :'<a href="?o=unfollow&d=' . $entry->user->id .'">Unfollow user</a>';

echo ' | ';echo ($entry->favorited == 'false') ?

'<a href="?o=favor&d=' . $entry->id .'">Mark message as favorite</a>' :'<a href="?o=disfavor&d=' . $entry->id .'">Remove message from favorites</a>';

echo '</small>';echo '</div>';

}?>

</body></html>

Listing 11 is best thought of as a giant conditional statement, which executes aparticular branch based on the value of the o parameter in the request URL:

• For o=follow, it looks for a screen name and uses the API toprogrammatically create a follower relationship with the correspondinguser.

• For o=unfollow, it looks for a numeric user identifier and uses the APIto remove the authenticated user's follower relationship with the specifieduser.

• For o=favor, it looks for a numeric message identifier and uses the APIto add the corresponding message to the authenticated user's favoriteslist.

• For o=disfavor, it looks for a numeric message identifier and uses theAPI to remove the corresponding message from the authenticated user'sfavorites list.

In each of the above cases, after performing the specified action, the scriptre-requests the Identi.ca public timeline through the API, parses the XML response,and displays the messages in a list, together with the appropriate controls.

Figure 6 displays an example of Listing 11 in action.

Figure 6. A browser-based dashboard for Identi.ca

ibm.com/developerWorks developerWorks®

Use PHP with Identi.ca, Part 2 Trademarks© Copyright IBM Corporation 2011 Page 19 of 24

Page 20: Use PHP with Identi.ca, Part 2 - grch.com.ar · Use PHP with Identi.ca, Part 2 List, search, and post microblog updates to Identi.ca with PHP and the StatusNet API Skill Level: Intermediate

Conclusion

Other articles in this series

• Use PHP with Identi.ca, Part 1

In this article, you worked through a crash course on how to integrate data from theIdenti.ca API into a PHP application using a combination of SimpleXML and the

developerWorks® ibm.com/developerWorks

Use PHP with Identi.ca, Part 2 Trademarks© Copyright IBM Corporation 2011 Page 20 of 24

Page 21: Use PHP with Identi.ca, Part 2 - grch.com.ar · Use PHP with Identi.ca, Part 2 List, search, and post microblog updates to Identi.ca with PHP and the StatusNet API Skill Level: Intermediate

Zend HTTP client library. The examples in this two-part article introduced you to thetwo main flavors of the API, showed you how to search Identi.ca content, illustratedhow to programmatically add, modify, and delete content, demonstrated how tomanage user subscriptions and favorites, and built a customized interface to a user'sIdenti.ca data.

As these examples illustrate, the Identi.ca API is a full-fledged, flexible interface fordevelopers ready to build creative new applications around microblogging services,content aggregation, and search. Play with it and see what you think.

ibm.com/developerWorks developerWorks®

Use PHP with Identi.ca, Part 2 Trademarks© Copyright IBM Corporation 2011 Page 21 of 24

Page 22: Use PHP with Identi.ca, Part 2 - grch.com.ar · Use PHP with Identi.ca, Part 2 List, search, and post microblog updates to Identi.ca with PHP and the StatusNet API Skill Level: Intermediate

Resources

Learn

• Use PHP with Identi.ca, Part 1: List, search, and post microblog updates toIdenti.ca with PHP and the StatusNet API (Vikram Vaswani, developerWorks,July 2011): Identi.ca is a popular free microblogging service for posting statusmessages and news. Learn to create, access, and search these messagesthrough the Identi.ca API and how to combine it with PHP to create dynamicWeb apps in this two-part article.

• The StatusNet API: Learn more about the StatusNet API and how to use it.

• Public timeline - Indenti.ca: Register for a free Identi.ca account and try amicroblogging service based on the Free Software StatusNet tool.

• The Zend_Http_Client component: Read more about an easy interface forperforming HTTP requests. Zend_Http_Client supports simple and complexfeatures expected from an HTTP client.

• The Zend_Feed component: Read more about consuming RSS and Atom feedswith a natural syntax for accessing elements of feeds, feed attributes, and entryattributes.

• Twitter's API documentation: Review the information and get started with theTwitter API.

• More articles by this author (Vikram Vaswani, developerWorks, August2007-current): Read articles about XML, additional Google APIs and othertechnologies.

• New to XML? Get the resources you need to learn XML.

• XML area on developerWorks: Find the resources you need to advance yourskills in the XML arena, including DTDs, schemas, and XSLT. See the XMLtechnical library for a wide range of technical articles and tips, tutorials,standards, and IBM Redbooks.

• IBM XML certification: Find out how you can become an IBM-CertifiedDeveloper in XML and related technologies.

• developerWorks technical events and webcasts: Stay current with technology inthese sessions.

• developerWorks on Twitter: Join today to follow developerWorks tweets.

• developerWorks podcasts: Listen to interesting interviews and discussions forsoftware developers.

• developerWorks on-demand demos: Watch demos ranging from productinstallation and setup for beginners to advanced functionality for experienced

developerWorks® ibm.com/developerWorks

Use PHP with Identi.ca, Part 2 Trademarks© Copyright IBM Corporation 2011 Page 22 of 24

Page 23: Use PHP with Identi.ca, Part 2 - grch.com.ar · Use PHP with Identi.ca, Part 2 List, search, and post microblog updates to Identi.ca with PHP and the StatusNet API Skill Level: Intermediate

developers.

Get products and technologies

• The Zend Framework: Download and build more secure, reliable, and modernWeb 2.0 apps and web services with widely available APIs.

• The identica-php library Download this complete, easy-to-use PHP library tointeract with the identi.ca platform.

• IBM product evaluation versions: Download or explore the online trials in theIBM SOA Sandbox and get your hands on application development tools andmiddleware products from DB2®, Lotus®, Rational®, Tivoli®, andWebSphere®.

Discuss

• XML zone discussion forums: Participate in any of several XML-relateddiscussions.

• The developerWorks community: Connect with other developerWorks userswhile exploring the developer-driven blogs, forums, groups, and wikis.

About the author

Vikram VaswaniVikram Vaswani is the founder and CEO of Melonfire, a consultingservices firm with special expertise in open-source tools andtechnologies. He is also the author of the books Zend Framework: ABeginners Guide and PHP: A Beginners Guide.

Trademarks

IBM, the IBM logo, ibm.com, DB2, developerWorks, Lotus, Rational, Tivoli, andWebSphere are trademarks or registered trademarks of International BusinessMachines Corporation in the United States, other countries, or both. These and otherIBM trademarked terms are marked on their first occurrence in this information withthe appropriate symbol (® or ™), indicating US registered or common lawtrademarks owned by IBM at the time this information was published. Suchtrademarks may also be registered or common law trademarks in other countries.See the current list of IBM trademarks.

ibm.com/developerWorks developerWorks®

Use PHP with Identi.ca, Part 2 Trademarks© Copyright IBM Corporation 2011 Page 23 of 24

Page 24: Use PHP with Identi.ca, Part 2 - grch.com.ar · Use PHP with Identi.ca, Part 2 List, search, and post microblog updates to Identi.ca with PHP and the StatusNet API Skill Level: Intermediate

Adobe, the Adobe logo, PostScript, and the PostScript logo are either registeredtrademarks or trademarks of Adobe Systems Incorporated in the United States,and/or other countries.Other company, product, or service names may be trademarks or service marks ofothers.

developerWorks® ibm.com/developerWorks

Use PHP with Identi.ca, Part 2 Trademarks© Copyright IBM Corporation 2011 Page 24 of 24