Tuesday, June 3rd, 2008

Twitter API Client Released

By Matt Williams

Here at Arc90, we love Twitter! Okay, okay – maybe not all of us love Twitter…some of us… I mean, well, at least one of us! Anyway, recently in need of Twitter’s services for an office side-project, we decided to write our own client that would integrate nicely with our existing PHP libraries.

The default content type for returned data is JSON (we love JSON!), but all of Twitter’s supported content types are available (XML, JSON, and in some cases RSS and ATOM).

Sound useful? Head on over to the lab and check it out!

Also…

Our Twitter client was largely inspired by the great web service clients available through the Zend Framework. Zend offers clients for several great web services like del.icio.us and Flickr; but Twitter is conspicuously absent from the list…While we’re not really sure why Zend has (so far) decided not to offer a Twitter client, we may also release a fully Zend-tastic version of the client leveraging Zend_Client_Rest, Zend_Date, etc in the near future. If you develop with Zend Framework and would find this useful, let us know!

58 Responses

  1. Gratis webwinkel said:

    Just can’t understand what people especially like about twitter. It’s just a lightweight accessible chat application. But I have to admit it

  2. Ben Sgro aka sk aka mr-sk said:

    Nice job Matt! Glad to see this up on the lab.

  3. Kris said:

    Hi,
    nice work. I would like to use this nice api.. Everything is well doumented, and it will be fun using it creating nice webapps with the interaction of twitter.
    One thing is missing, or am i blind, that is important for me and i can’t find a mailing list or something like this:
    can you tell me how i can sendMessage to the normal timeline, not as @reply as senMessage() is documented.
    The docs says: “Sends a new direct message to the specified user from the authenticating user.”, but twitter is more like a one to many messaging system. So most of my posts are just answering the question: “what are you doing?”.
    How can I send this?
    Thanx,
    Kris

  4. Matt Williams said:

    Hi Kris,
    I think the method that you’re looking for is updateStatus(). That will post a regular staus update to your timeline.
    ~ Matt

  5. Tom said:

    I’m going through your code and wondering why you didn’t use other methods for Twitter.php to determine its location and then use the require onces accordingly?
    I just went through and changed the two require_onces from Twitter.php to use $_ENV['PATH'] . ‘Twitter/Response.php’ (and same for Exception.php), then edited the require_once for Exception.php in Response.php to $_ENV['PATH'] . ‘Exception.php’. I don’t know why you didn’t do that, because modifying your paths seems a little confusing for the end user typically. I could have, sure, done it just fine the way you directed, but I didn’t understand _why_ I had to add something to the PATH.

  6. Matt Williams said:

    Hi Tom,
    There are definitely multiple ways to add the Twitter client (or any other library) to PHP’s include path, but I’m not sure that I understand what you’re suggesting.
    $_ENV['PATH'] is the system executable path, not related to PHP, and, like PHP’s include path, it’s really a list of paths. So, on a typical UNIX system, it might look something like this:
    /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin
    Using $_ENV['PATH'] in a require statement won’t work, because it’s not a valid path – it’s a colon-separated list.
    You can check your include path like this:
    echo(get_include_path());
    This usually looks something like this (on UNIX):
    .:/usr/share/php:/usr/share/pear
    To make a library accessible, you could drop it into a directory that’s already on your include path. There are several reasons why this might not be the best solution. First, any files that are placed on PHP’s global include path will be available to every PHP script on the server. You may or may not want this to happen. Second, if you do not control the server, you may not have access to these directories.
    My PHP applications use an MVC architecture with a front controller and a bootstrap file, so it’s easy to add directories to the include path for a single application by using set_include_path once in the bootstrap file.
    Let’s say that your public files live in a directory called “www”, and your library code lives in a directory called “lib” that’s next to the “www” directory. From a script in the “www” directory, you could add the “lib” folder to your include path as follows:
    $lib = dirname(dirname(__FILE__)) . “/lib”;
    set_include_path(get_include_path() . PATH_SEPARATOR . $lib);
    Yet another thing that you could do is to edit your php.ini file to add any directory that you want to the global include path.
    As far as the convention, it’s pretty standard for files in a library to assume that the library is on the include path and require other library files accordingly (e.g. require_once ‘Arc90/Service/Twitter/Exception.php’). Common PHP libraries such as PEAR (http://pear.php.net/) and Zend Framework follow the same pattern.
    ~ Matt

  7. S said:

    Hi, your library looks great, but what I really needed to use is methods to change profile design (background and colors) and this doesn’t seem to be available through the library. Is it just because you didn’t need this or it is not supported by the twitter API?

  8. Japh said:

    Hi Matt,
    Great library! I love it :)
    Not sure if you’d noticed or not, but Twitter do support changing the profile design via the REST API now: http://apiwiki.twitter.com/REST+API+Documentation#AccountMethods
    Are you versioning your library so I can tell if I’ve downloaded the latest or not? ;)
    Great work!

  9. Daniel said:

    Excellent Library, very well implemented, coded and easy to wrap your head around.
    Thanks a lot!

  10. Matt Williams said:

    Thanks for the feedback. I’m glad this library has been useful.
    In the interest of keeping up with Twitter’s API changes, I’ve set up a Google code repository for this project:
    http://code.google.com/p/arc90-service-twitter/
    You’ll find the original release there, as well as a new 2.0 release with several new features.
    The downloads for the 2.0 release include PhpDocs, so the new methods should be simple to follow.
    Bug reports, feature requests, etc are of course welcome.
    ~ Matt

  11. Mase said:

    Hey. I appreciate you making your library available. I have been playing around with it and found it very helpful. I have a quick question; sorry it is sort of a dumb $$ one though.
    After using many of the methods I finally decided to use the updateStatus method. At first I thought I needed to encode my string so I tried this using rawurlencode and also just urlencode. I also tried calling the method without encoding the string since it appears encoding is happening in your code.
    Anyway, my issue is that the text that always shows up on Twitter is displayed in the encoded form instead of plain text as desired. Am I missing something obvious in the documentation? If so I am sorry.
    Thanks in advance for your clarification/help!

  12. Daedeloth said:

    I’m having the same issue as Mase has; am I doing something wrong or is something messing this up? :)
    Thanks!
    Thijs.

  13. Stephen Beattie said:

    I’ve just submitted a patch (as an issue) on the Google Code project for this library to make the updateStatus() method work.
    Users can download patch and apply if working from SVN repository.

  14. james said:

    Hi,
    I’m trying to use your excellent Twitter client and am finding it relatively straightforward, and everything thusfar is working fine for me. Except just one thing….
    I cannot seem to send Twitter messages to @username using updateStatus(); – normal Twitter messages, not the private direct messages. If i try to send a message which contains @username it just seems to vanish into the ether – no error from the API, but no message posted either.
    Can you give me any pointers?
    Cheers.

  15. Karthik Murugan said:

    Great library. Any plans to use OAUTH?

  16. Matt Williams said:

    @Mase, @Daedeloth:
    Yes, this was a bug – not sure when it started, but it has been fixed – and thanks to @Stephen for submitting a patch.
    @james:
    There was a bug with @reply messages that was fixed as of the 2.1.2 release, about a week after your post.
    @Karthik:
    I definitely plan to add OAuth support soon. I’ve already started working on it, but I’m trying to figure out the best way to add support. I could just add an interface for OAuth tokens, request signing, etc and let people choose their own OAuth implementation and/or libraries… or I could add full support for those things as a part of the library itself. Since Twitter’s OAuth support is still in beta, and could change, this would mean that the library might need to evolve quickly to keep up for a while…
    To make things easier for users, I’m leaning towards the second option. Of course, if anyone would like to offer opinions on this, I’d be glad to hear them!
    In any case, expect some form of OAuth support, along with complete, working examples, to appear on the Google Code project page in the near future.
    ~ Matt

  17. Eric Martin said:

    Matt – I’m using your API Client for a Twitter based web-app and it works great! Thanks a bunch.
    Twitter now has mentions (replacing replies) and I was wondering if you were planning on adding that to the API? I have modified my copy for it, so I can add a patch if you like.

  18. Matt Williams said:

    @Eric -
    If you’d like to submit a patch on the Google Code project page, that would be great. Otherwise, I’ll release an update shortly. Looks like a simple change.
    Thanks!
    ~ Matt

  19. Sen said:

    Great job!
    By the way, your API documentation is not up to date here: http://www.arc90.com/_assets/Arc90_Service_Twitter/docs/

  20. Matt Williams said:

    @Sen -
    Thanks! I’m glad you’ve found this useful.
    The API docs linked from the blog post are from the original 1.0 release of this library. Each tagged release on the Google Code site comes bundled with up-to-date documentation as well as instructions on how to generate that documentation with PhpDocumentor (found in README).
    Thanks again for the compliments and for the heads-up!
    ~ Matt

  21. Thomas said:

    Is it possible to just do a search on a geo-location without putting a keyword in?

  22. v3 said:

    Hi!
    Thanks for your work :)
    Here’s some kind of bug report. You should use mb_strlen instead of regular strlen function when checking if message exceeds 140 characters. For example, strlen(“лол тест”) (russian) returns 15, and mb_strlen returns 8 as it should be. Don’t forget to call mb_internal_encoding(‘utf-8′) before.

  23. Matt Williams said:

    Thanks for the bug report. I’ll make the fix and post an update soon!
    Also, you can always post issues to the GoogleCode project:
    http://code.google.com/p/arc90-service-twitter/issues/list
    - Matt

  24. Arnaud said:

    Hey Matt,
    Was wondering if you had time to work on oAuth implementation? :)

  25. Jeroen Playak said:

    I can’t seem to update background and profile images. The functions return the profile of the account, and the old images are removed, but the new images do not appear… Anybody else had this problem and knows a solution?

  26. club penguin said:

    I would like to use this nice api.. Everything is well doumented, and it will be fun using it creating nice webapps with the interaction of twitter. One thing is missing, or am i blind, that is important for me and i can’t find a mailing list or something like this: can you tell me how i can sendMessage to the normal timeline, not as @reply as senMessage() is documented.

  27. Matt Williams said:

    @Arnaud -
    OAuth support is coming. We’ve gotten it working internally for TBuzz, so I just need to clean up the code and make sure not to break support for users who aren’t using OAuth yet (which is still a majority). If you’re desperate for support right away, email me and I’ll show you what we did to make OAuth work for us.
    @Jeroen -
    It seems like Twitter frequently has issues with caching. I’ve seen several instances where an updated image shows up long after it was posted. See here: http://twitter.com/twitterapi/status/1998378866 As long as the response from the Twitter API is successful, it’s probably a service-side problem and not a problem with your code or the library.
    @club penguin -
    The method that you’re looking for is updateStatus()
    - Matt

  28. Max said:

    Could you shoot me an email with the code supporting OAuth? We use your client and now are in need of OAuth support (ASAP).
    Cheers

  29. Patrick Curl said:

    I’d also love oauth support – I absolutely love your twitter api class its one of the best I’ve tried.
    One thing that might help is: http://github.com/jmathai/twitter-async/tree
    I’m currently trying to update twtfollow.com to use the above oauth api class in conjunction with your arc90.
    If they were combined into one it would make for one twitter api class to rule them all.

  30. Beau Giles said:

    I’m also pretty interested in oAuth support. :-)

  31. CD said:

    I installed it as suggested and am getting the following error when I try to run the script:
    Parse error: syntax error, unexpected T_CONST, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or ‘}’ in /includes/Arc90/Service/Twitter.php on line 44
    Any thoughts?
    Thanks,
    Chris

  32. Helen Hunt said:

    Thanks alot for the Twitter API client -
    I have been going through the code on it’s host site on Google Code, and will check it out when I get home to my computer.
    Will let you know if anything is not flying in the right direction.

  33. Steve said:

    I’m trying out the client for the first time and am getting the same error as CD posted on the 16th. PHP version is 5.2.5.

  34. Matt Williams said:

    CD, Steve -
    Could you point me to the download that you’re using? I downloaded both the 2.2.0 release and the 2.2.2 release from the Google Code site and was unable to reproduce the error. It looks like a basic syntax error (missing a bracket or semicolon or something), but I couldn’t find such an error in the source.
    Thanks
    - Matt

  35. Steve said:

    I re-downloaded the tar.bz2 2.2 file from google and installed it to be sure that wasn’t the issue. Still same issue.

  36. Matt Williams said:

    I just downloaded the release that you mentioned:
    http://arc90-service-twitter.googlecode.com/files/Arc90_Service_Twitter.tar.bz2
    and I created a simple test file (inside the lib folder) with the following code:
    require_once ‘Arc90/Service/Twitter.php’;
    $twitter = new Arc90_Service_Twitter();
    echo $twitter->setSSL(FALSE)->getPublicTimeline();
    … and it returned the public timeline without any error.
    Are you sure you didn’t modify the file? Also, are you sure the version you downloaded is listed on the current downloads page?
    If so, could you update the Google Code ticket (http://code.google.com/p/arc90-service-twitter/issues/detail?id=9) with lines 42-46 of ‘Arc90/Service/Twitter.php’?
    Thanks
    - Matt

  37. Steve said:

    Yes downloaded straight from the google current downloads section. No I didn’t modify it. Do you still need the lines?

  38. Steve said:

    Same library using a test server running 5.2.4 and your script above works.

  39. Mat Williams said:

    Yeah, I have boxes running 5.2.6 and 5.2.9 (Zend Server), both of which work fine. What’s strange is that the error message looks a standard syntax error. It seems to be saying, “You can’t put a const declaration here”, which would make me think there was a missing bracket or a stray comment character or something. Since the same file works across previous and following versions of PHP, though, that’s clearly not the case. I’ll try to look into this later when I can set up 5.2.5 for testing. I’ll let you know if I find a fix.
    - Matt

  40. Mark Essel said:

    Heyo, interested in potentially using a library for easy status access for twitter. The application will be a product to serve as a foundation for a small company. Will the licensing on the arc90 library allow for this?

  41. Matt Williams said:

    Mark -
    Absolutely. The library uses the BSD license. Commercial use as well as private use are permitted with only the restrictions outlined in the license. Basically, any redistribution of the code must retain the original copyright notice, and the names of the original author and organization may not be used to endorse derivative software without permission. The complete license may be found with the source code, and also here:
    http://www.opensource.org/licenses/bsd-license.php
    - Matt

  42. Colin said:

    Matt,
    As a Twitter newbie, I am getting no errors using your library, but no results either!
    I am running on my dev m/c (Vista) – I use Eclipse w/PHP – I have curl installed.
    For example, I know that I have a few followers, but the following yields nothing:
    $lib_base_dir = …
    require_once($lib_base_dir . ‘/libs/twitter/Arc90/Service/Twitter.php’);
    $username = ‘…’;
    $password = ‘…’;
    $twitter = new Arc90_Service_Twitter($username, $password);
    $get_followers = $twitter->getFollowers(‘xml’);
    $p_get_followers = print_r($get_followers, true);
    echo($p_get_followers);
    echo $get_followers->getData() . “\n”;

    The results show as:
    Arc90_Service_Twitter_Response Object
    (
    [_metadata:protected] => Array
    (
    [url] => https://twitter.com/statuses/followers.xml
    [http_code] => 0
    [header_size] => 0
    [request_size] => 0
    [filetime] => -1
    [ssl_verify_result] => 0
    [redirect_count] => 0
    [total_time] => 0
    [namelookup_time] => 0
    [connect_time] => 0.11
    [pretransfer_time] => 0
    [size_upload] => 0
    [size_download] => 0
    [speed_download] => 0
    [speed_upload] => 0
    [download_content_length] => 0
    [upload_content_length] => 0
    [starttransfer_time] => 0
    [redirect_time] => 0
    )
    [_data:protected] =>
    )
    —>>> nothing from getData()
    What am I doing wrong?
    Colin

  43. Martin said:

    Hi,
    completely the same experience as previous post by Colin. I tried to play a little bit with it – if I ran my script ten times, eight of them returns HTTP code zero, no data. What

  44. Rich said:

    bump. ditto.

  45. Dan said:

    Hi,
    I came to post because I am having the same error. I get 0 response from the script :-(
    I’m sure it’s something silly I am not seeing but:
    set_include_path(get_include_path() . PATH_SEPARATOR . $path);
    require_once(‘Arc90/Service/Twitter.php’);
    echo ‘ Include Path –> ‘ . ini_get(‘include_path’) . ”;
    $twitter = new Arc90_Service_Twitter(‘danflood75′,’xxxx’);
    $response = $twitter->showStatus(’3904580′,’json’);
    $return = $response->getData();
    print_r( ‘Your Latest Tweet: ‘ . json_decode($return) );

  46. Dan said:

    That results in:
    Your Latest Tweet –>
    with no data. Once I get this going I’m sure I will very much enjoy this library. Very nice work! Thanks!

  47. Carlos Ligues said:

    To get more than 20 status from a Friend Timeline. In a $count parameter you can set the number of status to retrieve. In the “Twitter.php” page.
    public function getFriendsTimeline($format =’json’, $since =”, $page =0, $count = 50)
    {
    $requestedFormat = strtolower($format);
    $validFormats = array(‘json’, ‘xml’, ‘rss’, ‘atom’);
    $this->_validateOption($requestedFormat, $validFormats);
    $url = self::PATH_STATUS_FRIENDS . “.{$requestedFormat}”;
    $args = array();
    if(” !== $since)
    {
    $this->_validateDateString(‘since’, $since);
    $args []= ‘since=’ . urlencode(date(‘D j M Y G:i:s T’, strtotime($since)));
    }
    if(0 !== $page)
    {
    $this->_validateNonNegativeInteger(‘page’, $page);
    $args []= “page={$page}”;
    }
    if(0 !== $count)
    {
    $this->_validateNonNegativeInteger(‘count’, $count);
    $args []= “count={$count}”;
    }
    if(count($args))
    {
    $url .= ‘?’ . implode(‘&’, $args);
    }
    return $this->_makeRequest($url, $requestedFormat, true);
    }

  48. emov2k4 said:

    as implemented with SimpleXMLElement showuser?

  49. jakot05 said:

    Hi there!,
    Im trying to update the background image, but is not working :-S
    Dont now what Im doing wrong.
    Thanks for your help
    $twitter = new Arc90_Service_Twitter($user,$password);
    $image= “/path/to/twitter.jpg”; //Local file path of the image to be uploaded
    $response = $twitter->updateProfileBackgroundImage($image, $format =’json’);
    $return = $response->getData();
    print_r( json_decode($return) );

  50. Tom said:

    I’ve been toying around with the library for a little while and have been experiencing similar behavior as some of the other commenters.
    Namely, I’ve been getting an http_code of 0. I’ve got a short workaround, but it’s just a hack for now.
    Here’s the original code that doesn’t work:
    $twitter = new Arc90_Service_Twitter($username, $password);
    try
    {
    $response = $twitter->getFriendsTimeline();
    if($response->isError()) {
    echo “Error response: ” . $response->http_code;
    } else {
    echo “Else response: ” . $response->http_code;
    }
    }
    // catch it and keep going
    When the above code runs, the else case fires echoing “Else response: 0.
    I added the following line after instantiating the client:
    $twitter->setSSL(FALSE);
    And everything works exactly as expected.
    My environment is Windows 7, PHP 5.2.10, and Apache.

  51. David Chen said:

    Hi, Matt
    I searched around the web and was excited to find this library for twitter.
    I got the same problem with some commenters here that getData() method returning nothing…
    Fortunately, Tom above got a work around and I got it work finally. Many people will benefit from his post on this issue.
    I would also like to know further why this happens if anyone knows. Is it unique to Windows platform? Thanks to Tom too.
    David

  52. David Chen said:

    //set $username, $password
    $twitter = new Arc90_Service_Twitter($username, $password);
    $twitter->setSSL(FALSE);
    try
    {
    $response = $twitter->getFriendsTimeline();
    $return = $response->getData();

    if($response->isError())
    {
    echo $response->http_code;
    }
    print_r(json_decode($return)); //this line still doesn’t return anything.
    }
    catch(Arc90_Service_Twitter_Exception $e)
    {
    // Print the exception message (invalid parameter, etc)
    print $e->getMessage();
    }

    // but if I add print_r(json_decode($return)); here, it can print the content.

    Anybody has idea in this issue? Thanks.

  53. Clerio Aguiar said:

    I had been using the arc90-service-twitter code for a site with tools for twitter, but now I am facing difficults in adapting it to OAuth. Did you already implemented this adaptation?

  54. Ray said:

    Hi, Great Class, but @the moment OAuth is required so this can’t be used anymore… :(

  55. Karthik Murugan said:

    Guys,

    Get the OAuth version of this library from http://github.com/yemkay/arc90-twitteroauth

  56. Ramesh Kolli said:

    hi i am a beginner in php.
    In example.php the following line is there.
    $twitter->useOAuth(‘OAUTH_CONSUMER_KEY’, ‘OAUTH_CONSUMER_SECRET’, ‘USER_TOKEN’, ‘USER_SECRET’);

    here what is ‘USER_TOKEN’ and ‘USER_SECRET’? are they Userid and password of Twitter Account?

    Plz help me.

  57. Karthik Murugan said:

    @Ramesh

    They are not username/password. They are access tokens received from Twitter after user signed via OAuth to your site. You should first integrate Twitter OAuth signin with your website using Abraham’s twitterOAuth library

Leave a Comment