about warning invalid for foreach() in php again - php

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 } ?>

Related

How to remove a specific data from an API?

I'm working on a site which gives metrics of site, it uses API of gtmetrix. So i want to remove a specific data from the coming result but I just dont know how to do it. Some help would be appreciated!
<?php
require_once('service.inc.php');
$test = new Services_WTF_Test("email", "api_key");
$url_to_test = "https://google.me/";
echo "Testing $url_to_test\n";
$testid = $test->test(array(
'url' => $url_to_test
));
if ($testid) {
echo "Test started with $testid\n";
}
else {
die("Test failed: " . $test->error() . "\n");
}
echo "Waiting for test to finish\n";
$test->get_results();
if ($test->error()) {
die($test->error());
}
$testid = $test->get_test_id();
echo "Test completed succesfully with ID $testid\n'<br>";
$results = $test->results();
if ($results): ?>
<?php
foreach($results as $result => $data): ?>
<strong><?php $ukey = strtoupper($result);
echo $ukey; ?>:</strong>
<?php echo $data; ?><br><br>
<?php endforeach;
endif;
?>
The Output Is:
FIRST_CONTENTFUL_PAINT_TIME: 1495
PAGE_ELEMENTS: 44
REPORT_URL: https://gtmetrix.com/reports/google.me/BFylJNX3
REDIRECT_DURATION: 0
FIRST_PAINT_TIME: 1495
DOM_CONTENT_LOADED_DURATION:
DOM_CONTENT_LOADED_TIME: 1908
I want to remove the 3rd data from the api REPORT_URL:
You can skip REPORT_URL in foreach
$ukey = strtoupper( $result );
if( $ukey != 'REPORT_URL' ) {
echo '<strong>' . $ukey . '</strong>';
echo $data . '<br><br>';
}

How to assign a PHP expression to a PHP variable

I need to do something like
$var = "Hello World ..the value is <?php echo 'XYZ' ?>";
Any help will be highly useful. I am stuck in this from the very long time but not able to acheive this. please help
Below is my PHP code that I need to assigned again to php variable (this variable will be passed to return of my ajax call)
<div class="photo-post">
<h4 class="h4-1">Some data...</h4>
<?php
$i=0;
$unique_seq="888094499";
$pic_counter=1;
foreach (glob("target/*".$unique_seq."*") as $filename)
{
$i++;
}
$total_pics=$i;
echo "<div id='post-photo-slider'>";
if($i>1)
{
echo "<a href='#' class='control_next_photo'>></a>";
echo "<a href='#' class='control_prev_photo'><</a>";
}
echo "<ul>";
foreach (glob("target/*".$unique_seq."*") as $filename)
{
echo "<li>";
echo "<div class='photos-slide-container'>";
echo "<img src='".$filename."' width='540px' height='225px'>";
echo "<span class='count-span-photos'>".$pic_counter." of ".$total_pics."</span>";
echo "</div>";
echo "</li>";
$pic_counter++;
}
if ($i==1)
{
echo "<li></li>";
}
echo "</ul>";
echo "</div><!-- post-photo-slider END -->";
echo "<hr class='hr4'>";
?>
</div><!-- photo end -->
you cannot do it in this way
$var = "Hello World ..the value is <?php echo 'XYZ' ?>";
when you return this string to your javascript php code cannot be execute on client side!!!!
why do not return do this simple way?
$var = "Hello World ..the value is " . "XYZ";

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;
}
}

serial number for faq displayed from admin

I am using the following code for display questions and answers from admin.
<?php
$select_faq = "Select `intFaqid`, `varQuestion`,`varAnswer` FROM `tbl_faq`";
$selectfaq_result = mysql_query($select_faq);
$select_faqnum = mysql_num_rows($selectfaq_result);
if($selectfaq_result > 0)
{
while($fetch_faq = mysql_fetch_array($selectfaq_result))
{
$faqid = $fetch_faq['intFaqid'];
$fquestion = strip_tags(ucfirst(stripslashes(nl2br($fetch_faq['varQuestion']))));
$fanswer = strip_tags(ucfirst(stripslashes(nl2br($fetch_faq['varAnswer']))));
?>
<h3><?php echo $fquestion; ?></h3>
<p><?php echo $fanswer; ?></p>
<?php
}
}
?>
I need to display the question number before the question. I used the following code for display the question number.
<?php
$questionno = 1;
$numberlimit = $select_faqnum;
while($questionno<=$numberlimit)
{
echo $questionno;
$questionno++;
}
?>
But i doesn't know how to display the question number before the question by combining both the codes. I need the output should display the question with question number. How can i do that?
Am I missing something? I am not sure why you would make it so complex.
Since your recordset is already determining the number of rows, why not just do this:
if($selectfaq_result > 0)
{
//initialise your variable
$question_number = 0;
while($fetch_faq = mysql_fetch_array($selectfaq_result))
{
//increment your variable
$question_number++;
$faqid = $fetch_faq['intFaqid'];
$fquestion = strip_tags(ucfirst(stripslashes(nl2br($fetch_faq['varQuestion']))));
$fanswer = strip_tags(ucfirst(stripslashes(nl2br($fetch_faq['varAnswer']))));
?>
//concatenate the string to include the variable.
//Don't forget to leave a space after it so it looks pretty
<h3><?php echo $question_number . ": " . $fquestion; ?></h3>
<p><?php echo $fanswer; ?></p>
<?php
}
Your line number will finish when you run out of records
<?php
$select_faq = "Select `intFaqid`, `varQuestion`,`varAnswer` FROM `tbl_faq`";
$selectfaq_result = mysql_query($select_faq);
$select_faqnum = mysql_num_rows($selectfaq_result);
if($select_faqnum > 0)
{
$question_number = 0;
while($fetch_faq = mysql_fetch_array($selectfaq_result))
{
$question_number++;
$faqid = $fetch_faq['intFaqid'];
$fquestion = strip_tags(ucfirst(stripslashes(nl2br($fetch_faq['varQuestion']))));
$fanswer = strip_tags(ucfirst(stripslashes(nl2br($fetch_faq['varAnswer']))));
?>
<h3><?php echo "$question_number. $fquestion"; ?></h3>
<p><?php echo $fanswer; ?></p>
<?php
}
}
?>
is that what you are looking for ?

Categories