Twitter Get User Status values using API and is there a limit? - php

All,
I have the following code to grab a twitter status and display it back to the user:
if( ! $tweet ) {
//$format = 'json';
//$contents = file_get_contents( "http://api.twitter.com/1/statuses/user_timeline/{$username}.{$format}", 0, $context );
//$contents = file_get_contents(" https://api.twitter.com/1/statuses/user_timeline.json?screen_name={$username}&count={$how_many}", 0, $context );
$url = "http://api.twitter.com/1/statuses/user_timeline.json?screen_name={$username}&count={$how_many}";
$curl = curl_init();
curl_setopt( $curl, CURLOPT_URL, $url );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1 );
$contents = curl_exec( $curl );
curl_close( $curl );
if ( ! empty( $contents ) ) {
// Decode it.
$tweet = json_decode( $contents );
// Cache it for next time.
//set_transient( $id.'-'.$username, $tweet, 60*60*3 ); // 3 hour cache
}
}
// Check to make sure we have a tweet and display it.
if ( is_array($tweet) && isset($tweet[0]->id_str)) {
do_action( 'themeblvd_twitter_slider', $tweet, $options, $username, $slider_id );
} else {
$output = '<span class="tweet-icon '.$options['icon'].'"></span>';
$output .= 'We experienced an error with Twitter! Please check back soon for our reviews!';
}
return $output;
So basically I'm trying to determine if I've already fetched some tweets and if not go fetch them and then pass them back to the loop below to display them to the user.
<?php
foreach($tweet as $t){
?>
<li class="slide tight <?php echo $classes; ?>">
<div class="slide-body">
<div class="grid-protection">
<?php
echo '<span class="tweet-icon '.$options['icon'].'"></span>';
echo '<a href="http://twitter.com/'.$username.'/status/'.$t->id_str.'" target="_blank">';
echo $t->text;
echo '</a>';
?>
</div><!-- .grid-protection (end) -->
</div><!-- .slide-body (end) -->
</li>
<?php
}
?>
For some reason I'm getting the error message saying that they can't be displayed. If I keep the limit to like 10 it displays fairly consistently without an error. If I increase the limit to like 50 or 85 I get the error message saying that twitter is having a problem. Has the API changed recently? Do they have new limits? Any ideas on why I can't display the 85 tweets?
Thanks in advace!

I found out that you can actually determine if you've reached your limit yet or not but calling the following URL:
https://api.twitter.com//1/account/rate_limit_status.json
What I did was check the response in this before actually trying to call the user status API. My code to check the rate limit looks like the following:
$url_check_limit = "https://api.twitter.com//1/account/rate_limit_status.json";
$curl_limit = curl_init();
curl_setopt( $curl_limit, CURLOPT_URL, $url_check_limit );
curl_setopt( $curl_limit, CURLOPT_RETURNTRANSFER, 1 );
$contents_limit = curl_exec( $curl_limit );
curl_close( $curl_limit );
if ( ! empty( $contents_limit ) ) {
// Decode it.
$tweet_limit = json_decode( $contents_limit );
}
if ( $tweet_limit->remaining_hits == "0" ){
$no_tweets = true;
echo "We've reached out rate limit";
}else{
//Execute the Twitter user_status API from my original question
}
This allows me to avoid keep calling the twitter API if I hit my limit already. If I didn't hit my limit I call the code in my original question and display the tweets to the user. Hope this helps someone!

Related

Trying to add $var to a URL in a Curl URL

So I have looked through stack overflow and google and cant find a good example of what I need.
I have a URL within Curl and i have a session variable i need to add to the URL (print out as string).
Question
how do i do this?
Here is my code
<?php
session_start();
echo $_SESSION['userID'];
$userId = $_SESSION['userID'];
$service_url = 'http://localhost/app/api/user/$userId.xml';
I have tried
$service_url = 'http://localhost/app/api/user/echo $userId.xml';
and
$service_url = 'http://localhost/app/api/user/<?php echo $userId ?>.xml';
UPDATE
Ok full code, so if I change the URL to
$service_url = 'http://localhost/app/api/user/1.xml';
everything works, however I need the code to be dynamic depending on the session var
currently the session var $_SESSION['userID']; is 1
so the current code should work in the same way as if the URL was
`$service_url = 'http://localhost/app/api/user/1.xml';`
but it dose not
<?php
session_start();
echo $_SESSION['userID'];
$userId = $_SESSION['userID'];
$service_url = "http://localhost/app/api/user/{$userId}.xml";
$session_cookie = file_get_contents( 'session_cookie.txt' );
// set up the request
$curl = curl_init( $service_url );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true ); // have curl_exec return a string
curl_setopt( $curl, CURLOPT_COOKIE, "$session_cookie" ); // use the previously saved session
// make the request
curl_setopt( $curl, CURLOPT_VERBOSE, true ); // output to command line
$response = curl_exec( $curl );
curl_close( $curl );
print "RESPONSE:\n";
var_dump( $response );
$xml=simplexml_load_file("$service_url") or die("Error: Cannot create object");
echo $xml->name . "<br>";
echo $xml->roles->item . "<br>";
echo $xml->timezone . "<br>";
Instead I get errors
Warning: simplexml_load_file
and
Warning: simplexml_load_file(): I/O warning : failed to load external entity "http://localhost/app/api/user/1%3Cbr%3E.xml" in C:\wamp64\www\mytest\testfolder\authenticated.php on line 23
Try
$service_url = "http://localhost/app/api/user/{$userId}.xml";
Change ' to ".
Let me explain why.
The difference ' to " is that " will parse $phpVariables.
So $service_url = "http://localhost/app/api/user/$userId.xml"; or $service_url = "http://localhost/app/api/user/{$userId}.xml";
If for some reason you want to keep single quotes you can do this:
$service_url = 'http://localhost/app/api/user/'.$userId.'.xml';
Why not CONCAT them?
$service_url = 'http://localhost/app/api/user/'.$userId.'.xml';

PHP - Iterate over google results

I have a simple CURL script that searches Google for "Batman", then saves the result in a file...
Can someone tell me a good way of iterating through the file to find each of the search results title and URL, please?
This is my code:
function get_remote_file_to_cache()
{
$the_site = "https://www.google.se/webhp?sourceid=chrome-instant&rlz=1C5CHFA_enSE555SE556&ion=1&espv=2&ie=UTF-8#newwindow=1&q=batman";
$curl = curl_init ();
$fp = fopen ( "temp_file.txt", "w" );
curl_setopt ( $curl, CURLOPT_URL, $the_site );
curl_setopt ( $curl, CURLOPT_FILE, $fp );
curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, TRUE );
curl_exec ( $curl );
$httpCode = curl_getinfo ( $curl, CURLINFO_HTTP_CODE );
if ($httpCode == 404)
{
touch ( 'cache/404_err.txt' );
} /*
* else { touch('cache/'.rand(0, 99999).'--all_good.txt'); }
*/
else
{
$contents = curl_exec ( $curl );
fwrite ( $fp, $contents );
}
curl_close ( $curl );
fclose ( $fp );
}
echo rand(1, 425).get_remote_file_to_cache();
You can search trough the HTML using DOMDocument and DOMXPath
// Temp:
$sPageHTML = '<html><head></head><body><div class="test">Text here</div></body></html>';
$oDomDocument = new DOMDocument ( );
$oDomDocument->loadHTML ( $sPageHTML );
// Now, search the DOM structure for all divs with class "test".
$oXPath = new DOMXPath ( $oDomDocument );
$results = $oXPath->query ( '//div[#class="test"]' );
// Loop through the results.
foreach ( $results as $result )
{
echo 'Innertext: ' . $result->nodeValue;
}
Good luck
If you are still searching, you can find an open source php google scraper here:
http://scraping.compunect.com/?scrape-google-search (scroll to bottom for the code)
You can just copy the DOM parsing routines from it, they work very well.

Function in PHP file doesn't work, when file is called using curl

I've got on my server PHP file, which download something using curl from another server, and save it to db in nested php function. This process is little time-consuming, when I open it in my browser, I must wait ca. 1 minute, but all downloaded records are correct.
Problem is in CRON wget/curl download. When I use
wget http://myserver/myscript.php, or curl http://myserver/myscript.php, connection is closed after 1 byte, and nothing happens on server...
Where make I mistake? Maybe some headers? Why wget/curl don't wait on end of my PHP function like browser? I hope, that require of wp-load.php (I must use for it some Wordpress functions) isn't problem?
Many thanks for responses
Code:
<?php
define('WP_USE_THEMES', false);
require_once("wp-load.php");
$licznik = 0;
// WP_Query arguments
$args = array (
'post_type' => array( 'easy-rooms' ),
'posts_per_page' => 30
);
// The Query
$query = new WP_Query( $args );
// The Loop
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
$fields = array(
"funkcja" => "lista_rezerwacji",
"id_pokoju" => get_the_ID()
);
$postvars = '';
foreach($fields as $key=>$value) {
$postvars .= $key . "=" . $value . "&";
}
rtrim($fields_string, '&');
$url = "http://some.remote.script.to.download.sth.by.curl";
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST, 1); //0 for a get request
curl_setopt($ch,CURLOPT_POSTFIELDS, $postvars);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT ,3);
curl_setopt($ch,CURLOPT_TIMEOUT, 120);
$response = curl_exec($ch);
curl_close ($ch);
echo $response;
//THIS IS FUNCTION IN SOME WORDPRESS PLUGIN, WHICH DOESN'T WORK WHEN I WGET/CURL THIS SCRIPT
set_reservations($response, get_the_ID());
$licznik++;
}
} else {
// no posts found
}
// Restore original Post Data
print_r($licznik);
wp_reset_postdata();
?>

Getting Facebook Like count

I have integrated Facebook Like into my website.Now i need to get/list the count of the Facebook like in the Admin panel of my website. Is there any way to get this done?Need suggestions.Thanks in advance.
$url = 'http://graph.facebook.com/PAGE_OR_APP_ID';
echo '['.$url.']: '.json_decode(file_get_contents($url))->{'likes'};
In order to get the number of likes of any object using Facebook API, use a Facebook API of your choice and commands like this:
https://graph.facebook.com/< your object id>/
You will receive a JSON object and you can extract the number of likes from it:
{
"id": "567454",
"link": "http://www.facebook.com/pages/PHP-Developer/103146756409401",
"likes": 250,
"type": "page"
}
More info on https://developers.facebook.com/docs/reference/api/
The more direct / updated link for this topic on facebook is
https://developers.facebook.com/docs/reference/api/page/
function fbLikeCount($appid,$appsecret){
//Construct a Facebook URL
$json_url ='https://graph.facebook.com/'.$appid.'?access_token='.$appsecret;
$json = file_get_contents($json_url);
$json_output = json_decode($json);
//Extract the likes count from the JSON object
if($json_output->likes){
return $likes = $json_output->likes;
}else{
return 0;
}
}
Facebook - <?php echo fbLikeCount('app/page id here','token here'); ?>
You can achieve that using the Graph API (v3)
function checkFacebookReactions($url){
$access_token = 'YOUR-FACEBOOK-TOKEN'; // Generate a Facebook Token first
$api_url = 'https://graph.facebook.com/v3.0/?id=' . urlencode( $url ) . '&fields=engagement&access_token=' . $access_token;
$fb_connect = curl_init(); // initializing
curl_setopt( $fb_connect, CURLOPT_URL, $api_url );
curl_setopt( $fb_connect, CURLOPT_RETURNTRANSFER, 1 ); // return the result, do not print
curl_setopt( $fb_connect, CURLOPT_TIMEOUT, 20 );
$json_return = curl_exec( $fb_connect ); // connect and get json data
curl_close( $fb_connect ); // close connection
$body = json_decode( $json_return );
// Print each key values, if needed
foreach($body->engagement as $k=>$v){
echo $k .": " .$v ."<br>";
}
$count = $body->engagement->reaction_count; // Return only reactions (likes + other reactions)
return $count;
}
$url = "REPLACE-WITH-YOUR-URL"; // The url you want to fetch details from
checkFacebookReactions($url);
First, you will need to generate a Facebook token. You can fin plenty of resources that explain how to get a token. This one will do the trick: https://elfsight.com/blog/2017/10/how-to-get-facebook-access-token

How to retrieve Twitter search results dynamically using Ajax?

I'm building a Twitter application which depends on retrieving Twitter search results. It works fine but I still need to update the page to get the new tweets.
How to let the page refreshes itself dynamically just like Twitter Widgets, to show the new tweets ?
Here is my code, please show me how, because I tired many scripts and it doesn't work with me.
Twitter Class
<?php
class Twitter
{
public function __construct(){ }
public function searchResults( $search = null )
{
$url = "http://search.twitter.com/search.atom?q=" . urlencode( $search ) . "&lang=en&rpp=50";
$curl = curl_init();
curl_setopt( $curl, CURLOPT_URL, $url );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1 );
$result = curl_exec( $curl );
curl_close( $curl );
$return = new SimpleXMLElement( $result );
return $return;
}
}
?>
Test Class
<?php
require_once("twitter.class.php");
$Twitter = new Twitter;
$results = $Twitter->searchResults("usa");
foreach( $results->entry as $result )
{
echo "<h3><a href=\"". $result->author->uri ."\">". $result->author->name ."<a/></h3><img src=\"". $result->link[1]->attributes()->href ."\" style=\"float: left;\"><p>". $result->content."</p><div style=\"clear:both;\"> </div>";
}
?>
.
.
Waiting for your response :)
You could poll for changes through javascript / ajax, by setting up a timer that calls a function in Test Class which returns a list of tweets. Example (using jquery because I am no javascript expert):
$(function() {
function fetchTweets() {
$.ajax({
url: "testclass.php",
success: function(data) {
// Replace contents of one element with data
}
}
setInterval(fetchTweets(), 60000);
}

Categories