Na navigaci | Klávesové zkratky

Twitter for PHP

Twitter for PHP is a very small and easy-to-use library for sending messages to Twitter and receiving status updates with OAuth support.

Download Twitter for PHP 3.5

It requires PHP (version 5 or newer) with CURL extension and is licensed under the New BSD License. You can obtain the latest version from our GitHub repository or install it via Composer:

php composer.phar require dg/twitter-php

Twitter requires SSL/TLS as of January 14th, 2014. Update to the last version.

Getting started

Sign in to the http://twitter.com and register an application from the http://dev.twitter.com/apps page. Remember to never reveal your consumer secrets. Click on My Access Token link from the sidebar and retrieve your own access token. Now you have consumer key, consumer secret, access token and access token secret.

Create object using application and request/access keys:

$twitter = new Twitter($consumerKey, $consumerSecret,
	$accessToken, $accessTokenSecret);

Posting

The send() method posts your status. The message must be encoded in UTF-8:

$twitter->send('I am fine today.');

You can append picture:

$twitter->send('This is my photo', $imageFile);

Displaying

The load() method returns the 20 most recent status updates posted in the last 24 hours by you:

$statuses = $twitter->load(Twitter::ME);

or posted by you and your friends:

$statuses = $twitter->load(Twitter::ME_AND_FRIENDS);

or most recent mentions for you:

$statuses = $twitter->load(Twitter::REPLIES);

Extracting the information from the channel is easy:

<ul>
<?php foreach ($statuses as $status): ?>
	<li><a href="http://twitter.com/<?= $status->user->screen_name ?>">
		<?= htmlspecialchars($status->user->name) ?></a>:

		<?= Twitter::clickable($status) ?>

		<small>at <?= date("j.n.Y H:m", strtotime($status->created_at)) ?></small>
	</li>
<?php endforeach ?>
</ul>

The static method Twitter::clickable() makes links in status clickable. In addition to regular links, it links @username to the user’s Twitter profile page and links hashtags to a Twitter search on that hashtag.

Searching

The search() method provides searching in twitter statuses:

$results = $twitter->search('#nette');

The returned result is a again array of statuses.

Error handling

All methods throw a TwitterException on error:

try {
	$statuses = $twitter->load(Twitter::ME);
} catch (TwitterException $e) {
	echo "Error: ", $e->getMessage();
}

Additional features

The authenticate() method tests if user credentials are valid:

if (!$twitter->authenticate()) {
	die('Invalid name or password');
}

Other commands

You can use all commands defined by Twitter API 1.1. For example GET statuses/retweets_of_me returns the array of most recent tweets authored by the authenticating user:

$statuses = $twitter->request('statuses/retweets_of_me', 'GET', array('count' => 20));

Komentáře

  1. veena #1

    avatar

    Díky Davide, zrovna Twitter chceme použít v jednom novém “omračujícím ?” projektu. Tak jsi nám to jenom ulehčil!

    Díky, pokud se projekt povede, pozvu tě na pivo ;-D

    před 16 lety | reagoval [2] Inza
  2. Inza #2

    avatar

    #1 veena, Tak to nás bude víc, co dělají na “omračujících” projektech a pozvou tě na pivo:-)

    před 16 lety
  3. Marcus Povey #3

    avatar

    Twitter broke/fixed their API recently and now this library returns 417 when attempting to post.

    Fix: Add the following line to twitter.class.php:113 just after the other curl_setopt lines and be fore the if ($post)…

    curl_setopt($curl, CURLOPT_HTTPHEADER, array(‘Expect:’));

    před 15 lety | reagoval [4] David Grudl
  4. David Grudl #4

    avatar

    #3 Marcus Povey, thank you Marcus, I have updated it.

    před 15 lety
  5. Martin Ragg #5

    avatar

    I've s.th. “strange” – I'm using your class and normally all is working fine – today I twittered “Königinnen der Nacht” and it seems to me that the class “killed” some letters. On twitter always there was only “Köinnen der Nacht” – do you have an idea?
    (Directly from twitter all was working fine .. )
    best regards,
    martin

    před 15 lety | reagoval [6] David Grudl
  6. David Grudl #6

    avatar

    #5 Martin Ragg, And was the message encoded in UTF-8?

    před 15 lety
  7. Martin Ragg #7

    avatar

    #10 David Grudl – Oh sorry, my fault – there was no utf8_encode, I fixed my script and it seems to be working finde

    před 15 lety
  8. Ryan Taylor #8

    avatar

    Hello David. Thank you very much for writing this PHP class for Twitter. I have one question: is there anyway to return the status ID of a tweet using the send() method? Currently it looks as though you have it returning only a boolean true/false.

    Thanks again!

    před 15 lety | reagoval [10] David Grudl
  9. Robb Corrigan #9

    avatar

    Hello David, excellent API! I'm using this in a simple hobby project that I've built which allows people to tweet Google charts. http://twitcharts.com/

    I've given you a plug here: http://twitcharts.com/about.php

    Thanks again!

    před 15 lety
  10. David Grudl #10

    avatar

    #8 Ryan Taylor, Ryan I have updated send() method, it returns ID on success and false on failure now.

    před 15 lety
  11. Nathan #11

    avatar

    It seems that Twitter returns tweets in UTC time. Is there an easy way to make the time and date conform to my time zone?
    I saw something that might help, here: https://www.alephnaught.com/…one-problem/ but my php knowledge is too limited to implement it with your solution.

    Thanks,
    Nathan

    před 15 lety
  12. Dragon Jake #12

    avatar

    Díky Davide za aktualizaci! Už jsem měl plány, že podporu ve svém forku nějak zkompletním (třeba odstraním zbytečnou druhou knihovnu a zlepším celý proces autorizace, jak jsi udělal Ty) a nenechám ji v tomhle stavu “nějak to funguje na to, co potřebuju”. Jsem rád, že je mohu zapomenout a věnovat se jiným věcem ;]

    před 14 lety
  13. srigi #13

    avatar

    Hello David, thank for good job. But I got problem, maybe I'm just blind or stupid, but how do I get $accessToken and $accessTokenSecret. I think that sctript must run OAuth loop (my app, twitter, return to my app), but this isn't covered in this article. Can you please add short desctiption/tutorial on this?
    THX.

    před 13 lety | reagoval [14] David Grudl
  14. David Grudl #14

    avatar

    #13 srigi, RTFM 🙂 There is a readme.txt file with complete explanation.

    před 13 lety
  15. Fost #15

    avatar

    Hi David,

    Very nice! Just one question: Is there a way of changing the limit from 24 hours for load()?

    Thanks!

    před 13 lety
  16. Onecar #16

    avatar

    Hello,
    is there any way how to make links in $status->text active, so I can click right away? So far I only have almost plain text, only author is a link.
    Thanks for your response.

    před 13 lety | reagoval [17] David Grudl
  17. David Grudl #17

    avatar

    #16 Onecar, in last revision there is a method Twitter::clickable().

    před 13 lety
  18. martin131 #18

    avatar

    Ahoj, vrací se v poli i přímý odkaz na tweet? Plánuješ případně tuto možnost přidat??

    před 13 lety
  19. David Grudl #19

    avatar

    Ten se dá poskládat, viz příklady v článku.

    před 13 lety | reagoval [20] martin131
  20. martin131 #20

    avatar

    #19 David Grudl, Jsem asi slepý, ani po druhém dlouhém zkoumání jsem to v těch příkladech nenašel. :D Nakonec jsem se podíval do wiki Twitter API.

    před 13 lety
  21. David Grudl #21

    avatar

    How to get a list of followers?

    function getAllFollowers($userName, $twitter)
    {
    	$followers = array();
    	$cursor = '-1';
    	do {
    		$channel = $twitter->request('followers/ids', 'GET', array('cursor' => $cursor, 'screen_name' => $userName));
    		$followers = array_merge($followers, $channel->ids);
    		if (empty($channel->next_cursor_str)) {
    			return $followers;
    		}
    		$cursor = $channel->next_cursor_str;
    	} while (true);
    }
    
    // usage
    $followers = getAllFollowers('davidgrudl', new Twitter(...));
    před 10 lety
  22. Keith #22

    avatar

    How would I favorite a tweet?

    před 10 lety
  23. Keith #23

    avatar

    NM, figured it out:

    $status = $twitter->request(‘favorites/create’, ‘POST’, array(‘id’ ⇒ $status->id_str));

    před 10 lety
  24. GCube #24

    avatar

    Hi David,
    I knew that Twitter changed its auth method again using SSL this time, how we can update the class using SSL OAuth?
    Thanks in advance

    před 10 lety | reagoval [26] David Grudl
  25. drknickel #25

    avatar

    Easy solution:
    Just open twitter.class and change line 18 to
    const API_URL = ‘#stary-odkaz-#stary-odkaz-https://api.twitter.com/1.1/’;

    Thats it :)

    před 10 lety | reagoval [26] David Grudl
  26. David Grudl #26

    avatar

    #24 GCube, #25 drknickel I have released fixed version with SSL support

    před 10 lety
  27. fans #27

    avatar

    Hello David,

    How can I post a pic using this class?

    Thanks in advance.

    před 10 lety | reagoval [28] David Grudl
  28. David Grudl #28

    avatar

    #27 fans, Update to the last version, there is support for uploading pictures via Twitter::send($status, $imageFile).

    před 10 lety
  29. fans #29

    avatar

    Thanks a lot. Regards.

    před 10 lety
  30. Phil #30

    avatar

    Thanks so much David, what a great script. When I try to upload an image using
    Twitter::send($status, $image)
    I get this error:
    Error: Server error: couldn't open file “https://davidgrudl.com/images/david-grudl.jpg”

    I've tried lots of different images and all give the same error. Should I provide the image in this format?
    $tweet = $twitter->send(‘Happy Wednesday!’, ‘https://davidgrudl.com/images/david-grudl.jpg’);

    If I post text only without an image it works fine.

    Thanks,
    Phil

    před 10 lety | reagoval [31] David Grudl
  31. David Grudl #31

    avatar

    #30 Phil, maybe it works only with local images, stored on file system.

    před 10 lety
  32. Phil #32

    avatar

    Thanks David, that was it.

    před 10 lety
  33. Saed #33

    avatar

    Hi ,
    Great work but I get this error

    Fatal error: Uncaught exception ‘TwitterException’ with message ‘Server error: couldn't connect to host’ in /home/a8771684/public_html/twitter.class.php:256 Stack trace: #0 /home/a8771684/public_html/twitter.class.php(201): Twitter->request(‘search/tweets’, ‘GET’, Array) #1 /home/a8771684/public_html/default.php(17): Twitter->search(‘#Egypt’) #2 {main} thrown in /home/a8771684/public_html/twitter.class.php on line 256

    From this webpage https://web.archive.org/…y.comxa.com/

    Any idea how to resolve it ,thanks in advance

    před 10 lety
  34. jahrvos #34

    avatar

    Hi, thanks a lot for the code

    I get a server error 401
    What can I do?

    před 10 lety
  35. alex #35

    avatar

    David, I actually created a new function like so:

    public function sendGeo($message, $lat, $lng, $media = null)
    	{
    		return $this->request(
    	 'statuses/update',
    			'POST',
    			array('status' => $message,
    			'lat' => $lat,
    			'long' => $lng,
    			'display_coordinates' => true)
    		);
    	}
    před 10 lety
  36. CreativeWolf #36

    avatar

    Hi David,

    Great work!

    While using your example for fetching followers, I tried the following:

    <tr>
    <?php foreach ($followers as $follower ): ?>
    	<td>
    	<?php echo $follower; ?>
    	</td>
    <td><?php echo $follower->screen_name; ?> </td>
    	<?php endforeach ?>
    </tr>

    I'm getting an error message “Notice: Trying to get property of non-object in followers.php”

    Please point me how to fetch the Screen Name and User Name.

    Thanks

    CreativeWolf

    před 9 lety | reagoval [37] David Grudl
  37. David Grudl #37

    avatar

    #36 CreativeWolf, function loadUserFollowers() returns only ids of followers, see https://dev.twitter.com/…ollowers/ids. To fetch screen name use function loadUserInfoById().

    před 9 lety
  38. Dave #38

    avatar

    Thank you, David, for this useful library!
    I tried to get line breaks into a tweet. So in send.php I wrote:

    $tweet = $twitter->send( 'First Line \n Second Line \n Third Line' );

    This was the result: https://twitter.com/…068253995008

    Any hints for getting line breaks into a Tweet?

    Many thanks in advance!

    před 9 lety | reagoval [39] David Grudl
  39. David Grudl #39

    avatar

    #38 Dave, use double quotes ie. "First\nSecond line".

    před 9 lety | reagoval [40] Dave
  40. Dave #40

    avatar

    #39 David Grudl, Great! Works perfectly. Thank you very much!

    před 9 lety
  41. Steve #41

    avatar

    Hi David,
    Great work! All was going well until I did this…
    $tweet = $twitter->send(‘@username’,$imagefile);
    fails with
    Error: Server error: couldn't open file “username”

    Is it not possible to send a reply with an image please?
     – Steve

    před 9 lety | reagoval [42] David Grudl
  42. David Grudl #42

    avatar

    #41 Steve, fixed in 3.5, but it requires PHP >= 5.5.0

    před 9 lety
  43. Barry B #43

    avatar

    Can't tweet an image! Here is my code:

    $twitter = new Twitter($consumerKey, $consumerSecret, $accessToken, $accessTokenSecret);
    $image=“../images/banner.jpg”;
    try {
    $tweet = $twitter->send(“Visit our site at www.xyz.com”,$image);
    }
    catch (TwitterException $e) {
    echo 'Error: ' . $e->getMessage();
    }

    The above code sends the text ‘Visit our site at www.xyz.com’ but doesn't attach the image with it. What am I missing?

    před 9 lety
  44. fabio #44

    avatar

    Hi,
    I use you library with success, is very simple to use it, thanks!
    I want to add a http address to the tweet, how I can do it if my text and link exceed the 140 characters?
    Thank's in advance,
    Fabio

    před 8 lety
  45. Max #45

    avatar

    Hi,

    How can I get a mute function?

    před 7 lety
  46. Max #46

    avatar

    Try to make a mute-function but the page gives an error.

    Here my code:

    	{
    		return $this->request('mutes/users/create', [
    			'user_id' => $username,
    			'follow' => $count);
    	}
    před 7 lety
  47. dawood #47

    avatar

    hi david
    help me with uploading video

    před 6 lety
  48. thamman_neha #48

    avatar

    Hi David,
    I'm trying to upload image via upload method using local storage, only text is being posted on twitter, but not image, nor it gives any error regarding to image upload.

    před 5 lety

Tento článek byl uzavřen. Už není možné k němu přidávat komentáře.


phpFashion © 2004, 2024 David Grudl | o blogu

Ukázky zdrojových kódů smíte používat s uvedením autora a URL tohoto webu bez dalších omezení.