I know this has been discussed a lot here, but I still don't seem able to find aworking solution. Either it's out of date, it's the wrong programming-language or it's no longer supported.
All I want to do is: Get the last 'n' tweets from a public Twitter profile using PHP/JavaScript.
What API should I use best?
How do I keep it as lightweight as possible?
I can't use Node. js
I tried this, but I can't seem to get it to work, as simple as it may look like.
Simplest PHP example for retrieving user_timeline with Twitter API version 1.1
I've already registered for a developer account and created a "Twitter-App".
You can use this API, which I have used once and it works perfectly.
Download the file TwitterApiExchange.php from the repository above and you may use the following sample code to fetch tweets of a user:
<?php
echo '<pre>';
require_once('TwitterAPIExchange.php');
/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
$settings = array(
'oauth_access_token' => "",
'oauth_access_token_secret' => "",
'consumer_key' => "",
'consumer_secret' => ""
);
$url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
$requestMethod = "GET";
$user = "rootcss";
$count = 100;
if (isset($_GET['user'])) {
$user = $_GET['user'];
}
if (isset($_GET['count'])) {
$count = $_GET['count'];
}
$getfield = "?screen_name=$user&count=$count";
$twitter = new TwitterAPIExchange($settings);
$string = json_decode($twitter->setGetfield($getfield)->buildOauth($url, $requestMethod)->performRequest(), $assoc = TRUE);
if (isset($string["errors"][0]["message"])) {
echo "<h3>Sorry, there was a problem.</h3><p>Twitter returned the following error message:</p><p><em>" . $string['errors'][0]["message"] . "</em></p>";
exit();
}
foreach ($string as $items) {
echo "Time and Date of Tweet: " . $items['created_at'] . "<br />";
echo "Tweet: " . $items['text'] . "<br />";
echo "Tweeted by: " . $items['user']['name'] . "<br />";
echo "Screen name: " . $items['user']['screen_name'] . "<br />";
echo "Followers: " . $items['user']['followers_count'] . "<br />";
echo "Friends: " . $items['user']['friends_count'] . "<br />";
echo "Listed: " . $items['user']['listed_count'] . "<br /><hr />";
}
echo '</pre>';
?>
It worked perfectly for me, Let me know if you face any issues.
Related
I am attempting to search tweets within a given date range, using the twitterapiexchange wrapper.
Here is my code
require_once('TwitterAPIExchange.php');
$settings = array(
'oauth_access_token' => "xx",
'oauth_access_token_secret' => "xx",
'consumer_key' => "xx",
'consumer_secret' => "xx"
);
$url = "https://api.twitter.com/1.1/search/tweets.json";
$requestMethod = "GET"
$getfield = "?q=from:manutd&until:2018-01-20&since:2018-01-01";
$twitter = new TwitterAPIExchange($settings);
$string = json_decode($twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest(),$assoc = TRUE);
if(array_key_exists("errors", $string)) {echo "<h3>Sorry, there was a problem.</h3>
<p>Twitter returned the following error message:</p><p><em>".$string[errors][0]
["message"]."</em></p>";exit();}
foreach($string as $items)
{
echo "Time and Date of Tweet: ".$items['created_at']."<br />";
echo "Tweet: ". $items['full_text']."<br />";
echo "Tweeted by: ". $items['user']['name']."<br />";
echo "Screen name: ". $items['user']['screen_name']."<br />";
echo "Followers: ". $items['user']['followers_count']."<br />";
echo "Friends: ". $items['user']['friends_count']."<br />";
echo "Listed: ". $items['user']['listed_count']."<br /><hr />";
}
This returns the latest tweets from the specified user, the date field appears to be ignored.
Is it possible to search by date using the API ?
The search API supports this, but you have to assemble your query like so:
https://api.twitter.com/1.1/search/tweets.json?q=from%3Atwitterdev&result_type=mixed&count=2
Refer: https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
The query string above is the urlencoded form of:
so you will pass like
https://api.twitter.com/1.1/search/tweets.json?q=%3Afrom:manutd&until:2018-01-20&since:2018-01-01
The list of search operators can be found here.
I'm using the Binance REST API to get previous trade information:
Endpoint: https://api.binance.com/api/v1/trades?symbol=BTCUSDT
$btc_trades = file_get_contents('https://api.binance.com/api/v1/trades?symbol=BTCUSDT');
$btc_trades = json_decode($btc_trades, true);
$five_minutes_ago = strtotime('-5 minutes');
echo "five minutes ago: " . $five_minutes_ago . "<br><br>";
foreach ($btc_trades as $btc_trade) {
$btc_trade_time = strtotime($btc_trade['time']);
$btc_trade_total = $btc_trade['qty'] * $btc_trade['price'];
if ($btc_trade_time >= $five_minutes_ago) {
$btc_trade_time = $btc_trade['time'];
echo "Time: " . $btc_trade_time . "<br>";
echo "Qty: " . $btc_trade['qty'] . "<br>";
echo "Price: $" . $btc_trade['price'] . "<br>";
echo "Total: " . $btc_trade_total . "<br><br>";
}
}
I can confirm by testing that there are trades returned that meet the condition (happened less than five minutes ago) however nothing is returned in this case.
Are the timestamps formatted differently? It seems as if I have everything correct.
From Binance API (https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md):
All time and timestamp related fields are in milliseconds.
Thanks for the help!
change to
$btc_trade_time = $btc_trade['time']/1000
I am starting on PHP, and i need a little help, I have my php file ytpost.php with the following content:
EDIT: I have my code a little bit disorganized,
<?php
$yturl = $_POST['urlyt']; //gets a youtube url
$yturlhttp = str_replace("https","http",$yturl); //replaces HTTPS with http
$ytid = substr(strstr($yturlhttp, 'http://www.youtube.com/watch?v='), strlen('http://www.youtube.com/watch?v=')); //removes everything before the video ID
$apikey = "blabla"; //youtube api
$JSON = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=statistics&id=$ytid&key=$apikey"); //using youtube api to get video info
$json_data = json_decode($JSON, true);
$getvideoviews = $json_data['items'][0]['statistics']['viewCount'];
$getvideolikes = $json_data['items'][0]['statistics']['likeCount'];
$getvideodislikes = $json_data['items'][0]['statistics']['dislikeCount'];
$getvideofavorites = $json_data['items'][0]['statistics']['favoriteCount'];
$getvideocomments = $json_data['items'][0]['statistics']['commentCount'];
$paloma = "✔"; //checkmark in spanish
$tacha = "✘"; //cross in spanish
$minimumvideoviews = "4000"; //minimum video views to be accepted
$minimumvideolikes = "100"; //minimum video likes to be accepted
//echo "views: " . $getvideoviews . "<br/>"; //TESTING
//echo "likes: " . $getvideolikes . "<br/>"; //TESTING
//echo "dislikes: " . $getvideodislikes . "<br/>"; //TESTING
//echo "favorites: " . $getvideofavorites . "<br/>"; //TESTING
//echo "comments: " . $getvideocomments . "<br/>"; //TESTING
if ($getvideoviews < $minimumvideoviews) {
echo "$tacha you dont have the minimum views to qualify for VIP ($minimumvideoviews minimum)<br/>";
}
else{
echo "$paloma you do have the minimum views to qualify for VIP ($minimumvideoviews minimum)<br/>";
};
if ($getvideolikes < $minimumvideolikes) {
echo "$tacha you dont have the minimum likes on your video to qualify for VIP ($minimumvideolikes minimum)<br/>";
}
else{
echo "$paloma you do have the minimum likes on your video to qualify for VIP ($minimumvideolikes minimo)<br/>";
};
?>
my problem is the following, i need to display something if both youtube views and youtube likes are exactly or over $minimumvideoviews and $minimumvideolikes, thank you.
, I dont have an idea on how to accomplish this,
I'm working on json source from wunderground.com. As the example code displayed in the document. I can adjust and work out for some simple format. But I'm stuck with this one. I tried to googled every where but there's no solution.
Here's the sample codes:
<?php
$json_string = file_get_contents("http://api.wunderground.com/api/b8e924a8f008b81e/geolookup/conditions/q/IA/Cedar_Rapids.json");
$parsed_json = json_decode($json_string);
$location = $parsed_json->{'location'}->{'city'};
$temp_f = $parsed_json->{'current_observation'}->{'temp_f'};
echo "Current temperature in ${location} is: ${temp_f}\n";
?>
Well, I need some information like "Cedar Rapids" out of pws/station :
"pws": {
"station": [
{
"neighborhood":"Ellis Park Time Check",
"city":"Cedar Rapids",
"state":"IA",
"country":"US",
"id":"KIACEDAR22",
"lat":41.981174,
"lon":-91.682632,
"distance_km":2,
"distance_mi":1
}
]
}
(You can get all code by clicking this : http://api.wunderground.com/api/b8e924a8f008b81e/geolookup/conditions/q/IA/Cedar_Rapids.json )
Now the questions are:
What is this data called? (array, array in array?)
How could I pull this data out of the line?
Regards,
station is an array within the pws object.
To get the data, you can do something like this:
<?php
$json_string = file_get_contents("http://api.wunderground.com/api/b8e924a8f008b81e/geolookup/conditions/q/IA/Cedar_Rapids.json");
$parsed_json = json_decode($json_string);
$location = $parsed_json->{'location'}->{'city'};
$temp_f = $parsed_json->{'current_observation'}->{'temp_f'};
echo "Current temperature in ${location} is: ${temp_f}\n";
$stations = $parsed_json->{'location'}->{'nearby_weather_stations'}->{'pws'}->{'station'};
$count = count($stations);
for($i = 0; $i < $count; $i++)
{
$station = $stations[$i];
if (strcmp($station->{'id'}, "KIACEDAR22") == 0)
{
echo "Neighborhood: " . $station->{'neighborhood'} . "\n";
echo "City: " . $station->{'city'} . "\n";
echo "State: " . $station->{'state'} . "\n";
echo "Latitude: " . $station->{'lat'} . "\n";
echo "Longitude: " . $station->{'lon'} . "\n";
break;
}
}
?>
Output:
Current temperature in Cedar Rapids is: 38.5
Neighborhood: Ellis Park Time Check
City: Cedar Rapids
State: IA
Latitude: 41.981174
Longitude: -91.682632
I'm using PHP last.fm API to fetch artist image
I'd like to know how to cache the calls so that I don't need to make same call again and again. The API has facility to cache : DiskCache, SqliteCache but there is no documentation, could anyone please shed some light on it?
Below is my code :
<?php
require __DIR__ . "/src/lastfm.api.php";
// set api key
CallerFactory::getDefaultCaller()->setApiKey(LAST_FM_API_KEY);
// search for the Coldplay band
$artistName = "Coldplay";
$limit = 1;
$results = Artist::search($artistName, $limit);
echo "<ul>";
while ($artist = $results->current()) {
echo "<li><div>";
echo "Artist URL: " . $artist->getUrl() . "<br>";
echo '<img src="' . $artist->getImage(4) . '">';
echo "</div></li>";
$artist = $results->next();
}
echo "</ul>";
?>