Call data from Twitter API - twitter

I am trying to write some code in php to show on a website exactly how many times a particular url has been tweeted on Twitter.
I assume I use the info in this page;
http://api.tweetmeme.com/url_info?url=http://dori.co.nz/
But what code would I need to add to the header of a Wordpress theme to call those values?
Many thanks in advance!

<?php
$url = "http://api.tweetmeme.com/url_info?url=http://dori.co.nz/";
$test = file_get_contents($url);
$xml = simplexml_load_string($test);
echo $xml->story->url_count;
?>
Here we go.

Related

Hiding YouTube API for client using server

My inexperience has left me short of understanding how to hide an API Key. Sorry, but I've been away from web development for 15 years as I specialized in relational databases, and a lot has changed.
I've read a ton of articles, but don't understand how to take advantage of them. I want to put my YouTube API key(s) on the server, but have the client able to use them w/o exposure. I don't understand how setting an API Key on my server (ISP provided) enables the client to access the YouTube channel associated with the project. Can someone explain this to me?
I am not sure what you want to do but for a project I worked on I needed to get a specific playlist from YouTube and make the contents public to the visitors of the website.
What I did is a sort of proxy. I set up a php file contains the api key, and then have the end user get the YT content through this php file.
The php file gets the content form YT using curl.
I hope it helps.
EDIT 1
The way to hide the key is to put it in a PHP file on the server.
This PHP file will the one connecting to youtube and retrieving the data you want on your client page.
This example of code, with the correct api key and correct playlist id will get a json file with the 10 first tracks of the play list.
The $resp will have the json data. To extract it, it has to be decoded for example into an associative array. Once in the array it can be easily mixed in to the html that will be rendered on the client browser.
<?php
$apiKey = "AIza...";
$results = "10";
$playList = "PL0WeB6UKDIHRyXXXXXXXXXX...";
$request = "https://www.googleapis.com/youtube/v3/playlistItems?part=id,contentDetails,snippet&maxResults=" . $results .
"&fields=items(contentDetails%2FvideoId%2Cid%2Csnippet(position%2CpublishedAt%2Cthumbnails%2Fdefault%2Ctitle))" .
"&playlistId=" . $playList .
"&key=" . $apiKey;
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => $request,
CURLOPT_SSL_VERIFYPEER => false
));
$resp = curl_exec($curl);
if (curl_errno($curl)) {
$status = "CURL_ERROR";
}else{
// check the HTTP status code of the request
$resultStatus = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($resultStatus == 200) {
$status = "OK";
//Do something with the $resp which is in JSON format.
//Like decoding it into an associative array
} else {
$status = "YT_ERROR";
}
}
curl_close($curl);
?>
<html>
<!-- your html here -->
</html>
Note: CURLOPT_SSL_VERIFYPEER is set to false. This is in development. For prod it should be true.
Also note that using the api this way, you can restrict the calls to your api key bounding them to your domain. You do that in the googla api console. (Tip for production)

Accessing public Instagram content via Instagram API without expiring accesstoken

i want to show public contents from instagram related to a specific hashtag (everything works fine with that) but i can't to renew the access_token everytime it expires.
("do not assume your access_token is valid forever." -
https://www.instagram.com/developer/authentication/)
To renew it manually is not an option i have to make sure there is a valid access_token at ANY time without re-authenticating.
Any ideas or questions? :)
I have one idea, but without API (and access_token). You can make requests to the web-version of Instagram with ?__a=1 parameter. I do not know how long it will work but now there is workflow:
You want to show public content with hashtag space, for example.
Add it to url and add GET-parameter ?__a=1: https://www.instagram.com/explore/tags/space/?__a=1
Make the GET-request. It returns json with nodes in top_posts (8) and media (18). Each node has owner, caption, number of comments and likes. But the most important part is in thumbnail_src and display_src.
There is page_info in media object which helps to paginate results. You need end_cursor (for example, J0HWE9rjAAAAF0HWE9qvgAAAFiYA)
Add the value from end_cursor to the url: https://www.instagram.com/explore/tags/space/?__a=1&max_id=J0HWE9rjAAAAF0HWE9qvgAAAFiYA
Repeat 3-6 to get newest posts with specific hashtag.
Update to the ?__a=1 url param. This appears to have stopped working with users '/account/?__a=1' endpoints.:( Still works on tags apparently.
Instagram shut down their public API. Here's a quick and dirty workaround in PHP:
<?php
function getPublicInfo($username) {
$url = sprintf("https://www.instagram.com/$username");
$content = file_get_contents($url);
$content = explode("window._sharedData = ", $content)[1];
$content = explode(";</script>", $content)[0];
$data = json_decode($content, true);
return $data['entry_data']['ProfilePage'][0];
}
Not sure for how long it's gonna work. Here's one for Javascript.

extract private youtube playlist video links

I am trying to extract the video link of my private playlist. but i am unable to do
I used the below code to get the list
<?php
if(isset($_POST['send']))
{
$cont = json_decode(file_get_contents('http://gdata.youtube.com/feeds/api/playlists/'.$_POST['a'].'/?v=2')); ?>
<?php $feed = $cont->feed->entry; ?>
<?php if(count($feed)): foreach($feed as $item): // youtube start ?>
<?php echo $item->{'media$group'}->{'yt$videoid'}->{'$t'} ?>
<?php echo $item->title->{'$t'} ?>
<?php endforeach; endif; }?>
but this doesn't work. i need to extract only link with video title.
i have my account details with me how its possible using php
Since you want a private playlist, this will need to be an authenticated call, so you'll first have to set up an oAuth exchange. In PHP the easiest way to do this is with the gapi client; you can see more info (and get the library and sample code) here:
https://developers.google.com/youtube/v3/code_samples/php#retrieve_my_uploads
It will require you to use the client ID and secret for your registered app, though (don't forget to turn on the YouTube API v3 in the registered app!).
Once the oAuth is working, you can change the sample code listed above to very easily get your private playlist; starting with line 40, you'll have to use a call that's something like this:
$playlistResponse = $youtube->playlist->listPlaylists('contentDetails', array(
'id' => $_POST['a'], // assuming this variable represents the id of your playlist
));
You'll also have to somewhat modify the code after that block to be able to parse the playlist feed and get your info.

How To Get Twitter Followes_Count To echo with commas

I am working on pulling the number of twitter followers into my Wordpress page but running into a small problem I cannot figure out. I imagine it would be a quick fix...do you think you can help?
The issue is the output reads:
11131
I would like it to read:
11,131
You see the comma in the correct position...not sure how to get that to render in the right format. Here is the code I am working with:
<?php
$data = json_decode(file_get_contents('https://api.twitter.com/1/user/lookup.json?screen_name=erinschreyer'), true);
echo $data[0]['followers_count'];
?>
Any help is appreciated...
It would work with that:
<?php
$data = json_decode(file_get_contents('https://api.twitter.com/1/users/lookup.json?screen_name=erinschreyer'), true);
$followers = $data[0]['followers_count'];
echo number_format($followers);
?>
See number_format()

Using Twitter OAuth to authenticate API calls for trends

I am working on a website that allows the user to search for the top ten twitter trends in a city or country. At first I was only relying on Twitter's Rest API, but I was having a lot of rate limit issues (at school my rate limit disappears faster than I have a chance to use it). I know that authenticating my API calls will help me to better deal with this issue (Authenticated API calls are charged to the authenticating user’s limit while unauthenticated API calls are deducted from the calling IP address’ allotment).
I implemented #abraham's PHP library (https://github.com/abraham/twitteroauth), unfortunately my API calls aren't being authenticated. I know I have implemented #abraham's PHP library, because it prints out my user information at the end like it should. I have my twitter trend search underneath it but the API call isn't being authenticated. I am not sure how to fix this, and any help would really be appreciated!
This is what I use to get the top ten trends by country:
function showContent(){
// we're going to point to Yahoo's APIs
$BASE_URL = "https://query.yahooapis.com/v1/public/yql";
// the following code should only run if we've submitted a form
if(isset($_REQUEST['location']))
{
// set a variable named "location" to whatever we passed from the form
$location = $_REQUEST['location'];
// Form YQL query and build URI to YQL Web service in two steps:
// first, we show the query
$yql_query = "select woeid from geo.places where text='$location'";
// then we combine the $BASE_URL and query (urlencoded) together
$yql_query_url = $BASE_URL . "?q=" . urlencode($yql_query) . "&format=json";
//var_dump($location);
// show what we're calling
// echo $yql_query_url;
// Make call with cURL (curl pulls webpages - it's very common)
$session = curl_init($yql_query_url);
curl_setopt($session, CURLOPT_RETURNTRANSFER,true);
$json = curl_exec($session);
// Convert JSON to PHP object
$phpObj = json_decode($json);
// Confirm that results were returned before parsing
if(!is_null($phpObj->query->results)){
// Parse results and extract data to display
foreach($phpObj->query->results as $result){
//var_dump($result);
$woeid = $result[0]->woeid;
if (is_numeric ($location))
{
echo "<span style='color:red; padding-left: 245px;'>Please enter a city or a country</span>";
}
else if(empty($result)){
echo "No results found";
}
else {
/* echo "The woeid of $location is $woeid <br />"; */
}
}
}
$jsontrends=file_get_contents("http://api.twitter.com/1/trends/".$woeid.".json");
$phpObj2 = json_decode($jsontrends, true);
echo "<h3 style='margin-top:20px'>TRENDS: ".$phpObj2[0]['locations'][0]['name']."</h3> \r\n";
$data = $phpObj2[0]['trends'];
foreach ($data as $item) {
echo "<br />".$item['name']."\r\n";
echo "<br /> \r\n";
}
if(empty($item)){
echo "No results found";
}
}
}
I then add it to #abraham's html.inc file (along with some php to see the rate limit status) and html.inc is included in the index.php:
<h1>Top Twitter Trends</h1>
<form name='mainForm' method="get">
<input name='location' id='location' type='text'/><br/>
<button id='lookUpTrends'>Submit</button>
</form>
<?php showContent();
$ratelimit = file_get_contents("http://api.twitter.com/1/account/rate_limit_status.json");
echo $ratelimit;
?>
</div>
#abraham's index.php file has some example calls, and since my call doesn't look like this I think that is probably why it isn't being authenticated.
/* Some example calls */
//$connection->post('statuses/update', array('status' => date(DATE_RFC822)));
//$connection->post('statuses/destroy', array('id' => 5437877770));
//$connection->post('friendships/create', array('id' => 9436992));
//$connection->post('friendships/destroy', array('id' => 9436992));
Please help me find what I need to fix so that my API calls are authenticated.
update 10-21
I think in order to make an authenticated API call I need to include something like this is my code:
$connection->get('trends/place', array('id' => $woeid));
It didn't fix my problem, but maybe it is on the right track?
First off, you'll find that keeping your PHP and HTML separate will really help streamline your code and keep logical concerns separate (aggregating the data and displaying it are two different concerns)(many PHPers like MVC).
The code you have shared appears to be correct. My guess is that the issue lies in the creation of the OAuth connection, which should look something like:
<?php
/* Create TwitteroAuth object with app key/secret and token key/secret from default phase */
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $token,$secret);
Where CONSUMER_KEY and CONSUMER_SECRET are from your Trends Test app and $token and $secret are from the user signing in to twitter and allowing your app permission. Are all these values showing up when you create the TwitterOAuth object?
Also, be sure you update the config items in the twitteroauth.php file (specifically line 21 should be set to use the 1.1 API and line 29 should be set to 'json').

Resources