How can i set a limit on Fousquare API - php

I'm fetching check-in's a place's from Foursquare API. But, API gets all check-in's. I need only 5 check-in's. How can I set a limit?
my code:
<?php if(!isset($_GET['code']) && !isset($_COOKIE['access_token'])) {
$authorizeUrl = $fsObjUnAuth->getAuthorizeUrl($redirectUri);
} else {}
$creds = $fsObj->get("/venues/{$userId}/herenow");
$f=0;
foreach ($creds->response->hereNow as $item) {}
foreach ($item as $item2) {
foreach ($item2 as $item3) {
$f++;
if($item3->firstName) {
echo '<div class="user-normal">';
echo '<img src="'.$item3->photo.'" class="avatar" />';
echo '<span class="username-def">';
echo $item3->firstName; echo ' ';
echo $item3->lastName;
echo '</span>';
echo '</div>';
if ($f==5) break;
}
;};}; ?>
i try this apigee.com and is working http://prntscr.com/1phdin. apigee is creating oauth_token but I don't understand how. I get "invalid oauth_token" error because I can't create my own.

You can pass an optional parameter to set the limit
Foursquare Developer docs
So for example:
/venues/{$userId}/herenow?limit=5

Related

about warning invalid for foreach() in php again

Why am I getting this PHP Warning?
Invalid argument supplied for foreach()
I don't know, if my PHP trouble or not compatible, I have been change and update my PHP version.
this the code:
<?php
// Generate a latitude/longitude pair using Google Maps API
list($lat,$lng) = $foursquare->GeoLocate($location);
// Prepare parameters
$params = array("ll"=>"$lat,$lng");
// Perform a request to a public resource
$response = $foursquare->GetPublic("venues/search",$params);
$venues = json_decode($response);
?>
<?php foreach($venues->response->venues as $venue): ?>
<div class="venue">
<?php
if(isset($venue->categories['0']))
{
echo '<image class="icon" src="'.$venue->categories['0']->icon->prefix.'88.png"/>';
}
else
echo '<image class="icon" src="https://foursquare.com/img/categories/building/default_88.png"/>';
echo '<a href="https://foursquare.com/v/'.$venue->id.'" target="_blank"/><b>';
echo $venue->name;
echo "</b></a><br/>";
if(isset($venue->categories['0']))
{
if(property_exists($venue->categories['0'],"name"))
{
echo ' <i> '.$venue->categories['0']->name.'</i><br/>';
}
}
if(property_exists($venue->hereNow,"count"))
{
echo ''.$venue->hereNow->count ." people currently here <br/> ";
}
echo '<b><i>History</i></b> :'.$venue->stats->usersCount." visitors , ".$venue->stats->checkinsCount." visits ";
?>
</div>
<?php endforeach; ?>
i don't know the json data. but try this option. if i have the json may be i can't help you more detail.
<?php
// Generate a latitude/longitude pair using Google Maps API
list($lat,$lng) = $foursquare->GeoLocate($location);
// Prepare parameters
$params = array("ll"=>"$lat,$lng");
// Perform a request to a public resource
$response = $foursquare->GetPublic("venues/search",$params);
$venues = json_decode(json_decode($response, true));
?>
<?php if(!empty($venues['response']['venues']) && is_array($venues['response']['venues'])){ ?>
<?php foreach($venues['response']['venues'] as $venue){ ?>
<div class="venue">
<?php
if(isset($venue['categories']['0']['icon']['prefix']))
{
echo '<image class="icon" src="'.$venue['categories']['0']['icon']['prefix'].'88.png"/>';
}
else
echo '<image class="icon" src="https://foursquare.com/img/categories/building/default_88.png"/>';
echo '<a href="https://foursquare.com/v/'.$venue['id'].'" target="_blank"/><b>';
echo $venue['name'];
echo "</b></a><br/>";
if(isset($venue['categories']['0']))
{
if(property_exists($venue['categories']['0'],"name"))
{
echo ' <i> '.$venue['categories']['0']['name'].'</i><br/>';
}
}
if(property_exists($venue['hereNow'],"count"))
{
echo ''.$venue['hereNow']['count'] ." people currently here <br/> ";
}
echo '<b><i>History</i></b> :'.$venue['stats']['usersCount']." visitors , ".$venue['stats']['checkinsCount']." visits ";
?>
</div>
<?php } ?>
<?php } ?>

How to speedup by code?

is there a way to speed up my code? It takes about 15 seconds to load ... I don't really see a way to reduce my code... I just thought about inserting the values into database, so the user does not have to load new info every time.. but the thing is that my cron only allows 1 load per hour ... by loading new info on every load it gives me fresh information..
$q1=mysql_query("SELECT * FROM isara");
while($r1=mysql_fetch_array($q1)){
$named=$r1['name'];
$idd=$r1['id'];
$descd=$r1['desc'];
$online=check_online($named);
$char = new Character($r1['name'],$r1['id'],$r1['desc']);
if($online == "online"){
$char->rank = $i++;
}
else{
$char->rank = 0;
}
$arr[] = $char;
}
?>
<br />
<h2 style="color:green">Online enemies</h2>
<?php
foreach ($arr as $char) {
if($char->rank>=1){
echo "<a style=\"color:green\" href=\"http://www.tibia.com/community/?subtopic=characters&name=$char->name\">";
echo $char->name." ";
echo "</a>";
echo level($char->name)."<b> ";
echo vocation($char->name)."</b> (<i>";
echo $char->desc." </i>)<br />";
}
}
?>
<br />
<h2 style="color:red">Offline enemies</h2>
<?php
foreach ($arr as $char) {
if($char->rank==0){
echo "<a style=\"color:red\" href=\"http://www.tibia.com/community/?subtopic=characters&name=$char->name\">";
echo $char->name." ";
echo "</a>";
echo level($char->name)."<b> ";
echo vocation($char->name)."</b> (<i>";
echo $char->desc." </i>)<br />";
}
}
?>
As I wrote in the comment, fetch the page once instead of once for every name in the database.
Pseudo code for my comment:
users = <get users from database>
webpage = <get webpage contents>
for (user in users)
<check if user exists in webpage>
As mentioned in the comments you're calling a webpage for each entry in your database, assuming that's about 2 seconds per call it's going to slow you down a lot.
Why don't you call the page once and pass the contents of it into the check_online() function as a parameter so your code would look something like this which will speed it up by quite a few magnitudes:
$content=file_get_contents("http://www.tibia.com/community/?subtopic=worlds&worl‌​d=Isara",0);
$q1=mysql_query("SELECT * FROM isara");
while($r1=mysql_fetch_array($q1)){
$named=$r1['name'];
$idd=$r1['id'];
$descd=$r1['desc'];
$online=check_online($named,$content);
$char = new Character($r1['name'],$r1['id'],$r1['desc']);
if($online == "online"){
$char->rank = $i++;
}
else{
$char->rank = 0;
}
$arr[] = $char;
}
?>
<br />
<h2 style="color:green">Online enemies</h2>
<?php
foreach ($arr as $char) {
if($char->rank>=1){
echo "<a style=\"color:green\" href=\"http://www.tibia.com/community/?subtopic=characters&name=$char->name\">";
echo $char->name." ";
echo "</a>";
echo level($char->name)."<b> ";
echo vocation($char->name)."</b> (<i>";
echo $char->desc." </i>)<br />";
}
}
?>
<br />
<h2 style="color:red">Offline enemies</h2>
<?php
foreach ($arr as $char) {
if($char->rank==0){
echo "<a style=\"color:red\" href=\"http://www.tibia.com/community/?subtopic=characters&name=$char->name\">";
echo $char->name." ";
echo "</a>";
echo level($char->name)."<b> ";
echo vocation($char->name)."</b> (<i>";
echo $char->desc." </i>)<br />";
}
}
?>
and your check_online() function would look something like this:
function check_online($name,$content){
$count=substr_count($name, " ");
if($count > 0){ $ex=explode(" ",$name); $namez=$ex[1]; $nameused=$namez; }
else{ $nameused=$name; }
if(preg_match("/$nameused/",$content)){ $status="online"; }
else{ $status="offline"; }
return $status;
}
You can also do the following to make it faster
Stop using select * which is very bad on innodb
Put better indexes on your database to make the recordset return faster
Install PHP 5.4 as it's faster especially as you're creating a new object in each iteration
Use a byte code accelerator/cache such as xdebug
you should avoid using distinct (*) keyword in your SQL Query
for more information read this http://blog.sqlauthority.com/category/sql-coding-standards/page/2/

Tumblr V2 API PHP wrapper

I am trying to integrate a Tumblr blog into my website, using the TumblrPHP wrapper available at https://github.com/gregavola/tumblrPHP. This is code I'm using to view the posts on my site:
<?php
include ('lib/tumblrPHP.php');
$consumer = 'key';
$secret = 'key';
$tumblr = new Tumblr($consumer, $secret);
$posts = $tumblr->get('/blog/nyhetergaius.tumblr.com/posts');
foreach($posts->response->posts as $posts) {
?>
<h2><?php echo date('Y-m-d', $post->timestamp) ?></h2>
<?php if ($post['type'] == 'regular') { ?>
<?php echo $post{'body'}; ?>
<?php } ?>
<?php
if ($post->type == 'photo') {
foreach ($post->photos as $photo) {
?>
<img src="<?php echo $photo->alt_sizes[1]->url ?>" />
<?php
}
echo $post->caption;
}
else
echo $post->body;
?>
<?php
}
?>
I am using my own key and secret key, but even so I can only retrieve a default date for each post. What am I doing wrong? Is there an easier way to view the posts as they appear on the blog http://nyhetergaius.tumblr.com/? This is how the posts appear on my site: http://test.gaius.nu/om.php.
Thank you for your support.
I was able to make this work by replacing $post['type'] with $post->type etc..
foreach($posts->response->posts as $posts) {
$postDate = date('Y-m-d', $posts->timestamp);
echo "<h2>$postDate</h2>";
if ($posts->type == 'regular') {
echo $posts->body;
}
elseif ($posts->type == 'photo') {
foreach ($posts->photos as $photo) {
$imgURL = $photo->alt_sizes[1]->url;
echo "<img src=\"$imgURL\" />";
}
echo $posts->caption;
}
else
{
echo $posts->body;
}
}

Bad array? Bad foreach?

Sorry for the huge ignorance on the topic, but I really have no idea where to look other than this website when I come into trouble with my PHP.
What I'm trying to do here is use pre-designated IDs to call particular movies from a database. But all I get is an 'Invalid argument supplied for foreach()' message on the second and third foreach's below.
Here's my code in the head:
//Custom lists of movies to bring in
//New Releases list
$films_new_releases = array(40805, 46705, 41630, 44564, 39451, 20352, 43933, 49009, 49797, 42194);
//Most Popular list
$films_most_popular = array(27205, 16290, 10138, 41733, 37799, 18785, 19995, 17654, 10140, 12162);
//Get information from address bar
$list = $_GET['l'];
if ($list == 'new releases') {
$list_chosen = $films_new_releases;
}
elseif ($list == 'most popular') {
$list_chosen = $films_most_popular;
}
else {
$list_chosen = $films_new_releases;
}
And in amongst the body:
// Loop through each film returned
foreach ($list_chosen as $list_chosen_film) {
$films_result = $tmdb->getMovie($list_chosen_film);
$film = json_decode($films_result);
// Set default poster image to use if film doesn't have one
$backdrop_url = 'images/placeholder-film.gif';
// Loop through each poster for current film
foreach($film->backdrops as $backdrop) {
if ($backdrop->image->size == 'poster') {
$backdrop_url = $backdrop->image->url;
}
}
echo '<div class="view-films-film">
<img src="' . $backdrop_url . '" alt="' . $film->name . '" />
<div class="view-films-film-snippet">
<h2>' . $film->name . '</h2>';
if ($film->certification != null) {
echo '<img src="images/bbfc-' . strtolower($film->certification) . '.png" alt="" />';
}
echo ' <h3>Starring</h3>
<p>';
$num_actors = 0;
foreach ($film->cast as $cast) {
if ($cast->job == 'Actor') {
echo '' . $cast->name . ' ';
$num_actors++;
if ($num_actors == 5)
break;
}
echo ' </p>
<h3>Director</h3>
<p>';
foreach ($film->cast as $cast) {
if ($cast->job == 'Director') {
echo '' . $cast->name . ' ';
}
}
echo ' </p>
</div>
</div>';
}
// End films
}
The little testing I've done is checking what $list_chosen, $list_chosen_film, $films_result and $film actually contain by printing them at the bottom of the page.
$list_chosen shows - Array, $list_chosen_film shows - 42194, $films_result shows the entire JSON string, $film shows - Array.
Try adding:
print_r($film->backdrop);
before the second foreach() loop. Before the error message it won't be an array or it will contain zero elements (not allowed). If you also add:
echo $films_result;
you will be able to debug it and fully understand what is wrong. If not, post the whole output in your question.
This happens, because - as error displayed by PHP informed you - you have provided wrong parameter to foreach loop, probably null or some other value. Make sure you are providing array to foreach.
Also, every time you use foreach, do it like that:
if (count($some_list) > 0) {
foreach ($some_list as $list_item) {
// code for each item on the list
}
} else {
// code when there is nothing on the list
}
This will ensure you will not see errors just because there is nothing on the list.
EDIT:
On the documentation page you can find some tip how to avoid such errors if the collection you are trying to iterate through is empty. Just cast the collection to array type:
foreach ((array) $some_list as $list_item) {
// code for each item on the list
}
Can you provide a dump of $film? The error is telling you that you are pointing to an object that cannot be iterated through (most likely null).

Twitter Oauth home timeline display with php

$hometime= $Twitter->get_statusesHome_timeline();
Fatal error: Uncaught exception 'Exception' with message 'SimpleXMLElement::__construct() expects parameter 1 to be string
<?php
include 'EpiCurl.php';
include 'EpiOAuth.php';
include 'EpiTwitter.php';
include 'key.php';
$Twitter = new EpiTwitter($consumerKey, $consumerSecret);
$oauthToken='xxxxxxxxxxxxxxxxxxxxxxx';
$oauthSecret='xxxxxxxxxxxxxxxxxxxxxxxxx';
// user switched pages and came back or got here directly, stilled logged in
$Twitter->setToken($oauthToken,$oauthSecret);
$user= $Twitter->get_accountVerify_credentials();
echo "<img src=\"{$user->profile_image_url}\">";
echo "{$user->name}";
$hometime= $Twitter->get_statusesHome_timeline();
$twitter_status = new SimpleXMLElement($hometime);
foreach($twitter_status->status as $status){
echo '<div class="twitter_status">';
foreach($status->user as $user){
echo '<img src="'.$user->profile_image_url.'" class="twitter_image">';
echo ''.$user->name.': ';
}
echo $status->text;
echo '<br/>';
echo '<div class="twitter_posted_at"><strong>Posted at:</strong> '.$status->created_at.'</div>';
echo '</div>';
}
?>
My best guess is that you might have turned off Warnings (and Notices) and that the
$hometime= $Twitter->get_statusesHome_timeline();
call doesn't return any xml but "false" because it can't connect (or something).
Did you try printing $hometime after the call ?
$hometime should be an array of status objects.
Try
<?php
$hometimeline = $Twitter->get_statusesHome_timeline();
foreach($hometimeline as $status){
echo '<div class="twitter_status">';
foreach($status->user as $user){
echo '<img src="'.$user->profile_image_url.'" class="twitter_image">';
echo ''.$user->name.': ';
}
echo $status->text;
echo '<br/>';
echo '<div class="twitter_posted_at"><strong>Posted at:</strong> '.$status->created_at.'</div>';
echo '</div>';
}

Categories