Chris Nizzardini, Salt Lake City Utah, Web Developer Specializing in LAMP+Ajax Since 2006

My Blog

Here is my awesome blog. You can find information on programming, linux, documentation, tips for code and database optimization, my thoughts and rants, and whatever else I feel like sharing. Feel free to contribute to the blog by posting comments and asking questions.
Programming

posting to and searching twitter with the twitter api and php

I asked a co-worker today if he ever used twitter. His response was “No, I have friends.” The feeling was mutual, however twitter seems very popular and its been a while since I’ve played around with an API. So I created a twitter account, and then began looking through the API documentation. I was happy to see they had support for JSON.

Its been a while since I played around with an API so I decided to dust of my web development API skills and create a Twitter class written to work in PHP 5.2.1. This class uses the native support for JSON, but I did include a bit of (untested) code for those of you using a sub par version of PHP. Just edit the include path for the JSON.php file and it should work. The file I’ve provided is a PHPS file, so you will need to chop the S of the end of the file name for it to work.

Download Twitter.class.php

Here is an example of using the class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
include_once('Twitter.class.php');
 
$twitter = new Twitter();
// it takes an array of search terms incase you want to search for a lot of stuff
$twitter->set_searchTermArr(array('twitter','obama','new york giants')); 
$twitter->search();
$array = $twitter->get_searchResultArr();
 
	foreach($array as $a)
	{
		if($a->results!=0)
		{
			echo 'twitter results for "'.$a->query.'"';
			foreach($a->results as $i)
			{
				echo $i->text.' user: '.$i->from_user.' created: '.$i->created_at;
			}
		}
	}

Now for updating your twitter account:

1
2
3
	$twitter->set_username('username');
	$twitter->set_password('password');
	$twitter->update('using twitter api to update this');

Related posts:

  1. using JSON to pass JavaScript arrays to PHP via Ajax
  2. Pass Objects and Arrays Between JavaScript and PHP with JSON
  3. Convert a PHP Object to an Array

Leave a Reply