<Martian Wabbit Productions>

Building a Simple Twitter PHP Class

August 16th, 2009 by Seich

preview

PHP is a very versatile scripting language. In this tutorial I will be explaining how to create a PHP class that will help you post and get information from a twitter account using the client URL library (cURL).

Tutorial Details

  • Program: PHP/Twitter API
  • Version: 1
  • Difficulty: Easy
  • Estimated Completion Time: 10 minutes

Step 1 – Starting up

Let’s begin. First, we will create a file named twit.php which will contain our class. Once created, we declare our class and name it twit.

1
2
3
4
<?php
class twit {//define class "twit"

}

Step 2 – The Constructor

We will now add our class’s public variables and its constructor. The constructor is a special function that will be run when we create a new instance of the class.

1
2
3
4
5
6
7
8
9
10
<?php
class twit {
public $username;
public $password;

function __construct($username, $password) {
$this->username = $username;
$this->password = $password;
}
}

Now we have defined the two variables that we will be using throughout the class. These will be defined when a new instance of the class is created, thanks to our __construct method.

Step 3 – Posting

It’s time to define our first method.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?php
class twit {
public $username;
public $password;

function __construct($username, $password) {
$this->username = $username;
$this->password = $password;
}
function postStatus($tweet) {
$ch = curl_init();//initiate curl session.
curl_setopt($ch, CURLOPT_URL, 'http://www.twitter.com/statuses/update.xml');//set URL to connect to.
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);//set mode to POST.
curl_setopt($ch, CURLOPT_POSTFIELDS, "status=".urlencode($tweet));//send status information.
curl_setopt($ch, CURLOPT_USERPWD, "$this->username:$this->password");//send login information.

$result = curl_exec($ch);//execute curl session.
$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);//get response code.

if ($http_status == 200) {//200 means the post was succesful.
return true;
} else {
return false;
}
curl_close($ch);//close curl connection.
}
}

The postStatus method will be used to tweet directly to our account, to achieve this we use the cURL to post using twitter’s api. The setup is simple and configured as specified on the twitter api page. The method returns true or false based upon the response code sent back from twitter this, makes the class easier to be used within another page in order to display success/error messages or trigger some other action.

Let’s try our class and see what we have so far.
Create another php file and try the following code in it. Make sure to replace USER and PASSWORD with your twitter username and password.

1
2
3
4
5
6
7
8
9
10
<?php
require("twit.php");

$twitter = new twit("USER", "PASSWORD");//replace these
if($twitter->postStatus("Test!")){
echo("Status Posted!");
}else{
echo("There was an error when posting the status to twitter.");
}
?>

If everything is working correctly you should see the post on your twitter account and it should appear as posted through the API.

1

Step 4 – Getting

Finally, we will define our second and last method which, is going to help us get the information of our last twitter status.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<?php
class twit {
public $username;
public $password;

function __construct($username, $password) {
$this->username = $username;
$this->password = $password;
}
function postStatus($tweet) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.twitter.com/statuses/update.xml');
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "status=".urlencode($tweet));
curl_setopt($ch, CURLOPT_USERPWD, "$this->username:$this->password");

$result = curl_exec($ch);
$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if ($http_status == 200) {
return true;
} else {
return false;
}
curl_close($ch);
}
function getStatus() {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://twitter.com/statuses/user_timeline/'.$this->username.'.xml');//set url to the user's timeline.
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERPWD, "$this->username:$this->password");
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_GET, 1);//set mode to get.

$result = curl_exec($ch);
$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

curl_close($ch);

if ($http_status != 200) {
return null;
}

$resultArray = simplexml_load_string($result);//load the result into a simplexml object.
return $resultArray->status;//return object.
}
}

This time we will be using the cURL’s get option, which will allow us to get the information from the twitter server.
In this method I am using a simplexml object to make the task of managing information easier, since we will be receiving a lot of data from the server.

Let’s try the new method out! Create a new PHP file and insert the following code into it. Once again, make sure to replace USER and PASSWORD with your corresponding twitter username and password.

1
2
3
4
5
6
7
8
<?php
require("twit.php");

$twitter = new twit("USER", "PASSWORD");//replace these
$tweeter2 = $tweeter->getStatus();
var_dump($tweeter2);

?>
2

You will get a lot of data, but since it’s stored in a simplexml object it is quite easy to manipulate it.
For example, if you wanted to get the text from your last post you could use:

1
2
3
4
5
6
7
<?php
require("twit.php");

$tweeter = new twit("Seich", "password");
echo($tweeter->getStatus()->text);

?>

Which would echo whatever you wrote in your last update. Using this same method you can access all of the data provided.

Conclusion

Twitter’s API is quite easy to manipulate. It is a very repetitive task though, so an object-oriented approach can help us making the process easier. Using these two methods as example, you should be able to expand the class or create your own approach to it. Nevertheless you should now be able to play with the Twitter API and manipulate Twitter’s data.

Further reading

I would recommend reading these in order to get a deeper view of what we covered in this tutorial.

  • Archive

  • Tags

    COmposing factorial Feed Feedburner font function Hello loop Music Noctorious PHP Script Tutorial type Updates
  • Downloads

  • Random Ads

  • 3 Responses to “Building a Simple Twitter PHP Class”

    1. Amit Choudhary says:

      good tutorial

    2. Alex Bongo says:

      Great tut Seich! Very simple, illustrative description and easy-to-grab examples. You’ve given more reason to explore and learn cURL usage now. Thanks Buddy!

    3. james says:

      Awesome!!! you just save me from a homework of college!

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    *

    You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>