Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get image url from tweets using the Twitter API

Tags:

I'm using this code:

require_once ("twitteroauth.php");  define('CONSUMER_KEY', 'XXX'); define('CONSUMER_SECRET', 'XXX'); define('ACCESS_TOKEN', 'XXX'); define('ACCESS_TOKEN_SECRET', 'XXX');  $toa = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);  $query = array(   "q" => "#Misiones",   "result_type" => "recent",   "include_entities" => "true" );  results = $toa->get('search/tweets', $query);  foreach ($results->statuses as $result) {    $user = $result->user->screen_name;   $text = $result->text; 

To get tweets whit the hashtag #Misiones(the name of the place where i'm live). Works fine but i'm trying to get the image url (if the tweet have some).
I tryed with $result->media and $result->media->media_url and other convinations without succcess.

like image 766
Gus Carracedo Avatar asked Apr 05 '14 22:04

Gus Carracedo


People also ask

How do you get a Twitter URL for a picture?

twitter URL then try right-clicking on the tweet and selecting View source (or similar). Use CTRL+F to search for pic. twitter and you should be able to find the URL there.

Is Twitter API legal?

The use of the Twitter API and developer products to create spam, or engage in any form of platform manipulation, is prohibited. You should review the Twitter Rules on platform manipulation and spam, and ensure that your service does not, and does not enable people to, violate our policies.


1 Answers

Tweet Entities are what you are looking for to access the pictures. Entities provide structured data from Tweets including expanded URLs and media URLs. They are located under the entities attribute in all Tweet objects from both Twitter REST and Streaming APIs.

As a result, to answer your question, if a Tweet contains one picture, its URL will be located here:

$media_url = $result->entities->media[0]->media_url; 

Below is a PHP snippet you can add to your existing foreach loop, it is a bit more elaborate to handle whether or not the Tweet contains media URLs:

if (isset($result->entities->media)) {     foreach ($result->entities->media as $media) {         $media_url = $media->media_url; // Or $media->media_url_https for the SSL version.     } } 
like image 183
Romain Huet Avatar answered Oct 21 '22 09:10

Romain Huet