I'm using working on building a WordPress plugin, that uses the Twitter api - but I'm very new to working with Twitter.
I currently have a keyword search form and results working
<?php
// get the keyword from url
$srchterm = $_GET['search_box'];
// encode it for the safe search
$srchterm = urlencode($srchterm);
// search the keyword using Twitter API
$srch_twitts = "http://search.twitter.com/search.atom?q=".$srchterm."";
// use curl to execute the Twitter URL
$twits = curl_init();
curl_setopt($twits, CURLOPT_URL, $srch_twitts);
curl_setopt($twits, CURLOPT_RETURNTRANSFER, TRUE);
$twi = curl_exec($twits);
// here we have the searched result in an array
$search_res = new SimpleXMLElement($twi);
//print_r($search_res);
?>
<?php
/* display the data */
$i = 0;
// displays the search keyword
echo "<p style='padding-left:10px; color:brown'>Your search term is: " . stripslashes($_GET['q']) . "</p>";
// tweets in an array. split it by foreach
// we need only 10 result so, use if condition
foreach ($search_res->entry as $result) if ($i++ < 10)
{
echo "<div id='tweets'>";
echo "<p>$i</p> ";
echo "<div class='avatar'><img src='". $result->link[1]->attributes()->href. "' /> </div>";
echo "<div class='twitcont'>";
echo "<div class='name'>". $result->author->name . "</div>";
echo "<div class='content'>" . $result->content ;
// convert the updated date of tweet to seconds
$twittedSeconds = time() - strtotime($result->updated);
$names = array('second', 'minute', 'hour', 'day', 'week', 'month', 'year');
$seconds = array( 1, 60, 3600, 86400, 604800, 2630880, 31570560);
// find the time difference between present time and tweet time
if($twittedSeconds > 0)
{
for($j = count($seconds) - 1; $j >= 0 ; $j--)
{
$interval = $seconds[$j];
if($twittedSeconds >= $interval)
{
$getTime = round($twittedSeconds / $interval);
if ($getTime > 1)
{
$names[$j] .= s;
}
$time = $getTime. ' ' . $names[$j] . ' ago';
break;
}
}
//echo the time difference
echo "<div class='time'> " . $time . "</div>";
}
echo "</div>";
echo "</div></div>";
}
?>
My question:
How can I integrate a tweet button for each result - this would allow the admin to (after searching twitter for keyword matches) tweet back on conversations.
Please see this example: http://screencast.com/t/2xBkTyUHT
Find the tweet id then attach a hyper link of this format
https://twitter.com/intent/tweet?in_reply_to={tweet id}
So the link might look like this.
$tweet_id = substr($entry->id, strrpos($entry->id, ':')+1);
echo "Reply";
More information can be found here. Twitter Web Intents
Note: You put echo "<div id='tweets'>"; in a loop. Means DOM will have multiple elements with same id. Correct it either using class or put it outside the loop.
Related
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 am trying to create a small instagram app in PHP only (no database) and without getting an access_token (just my client_id). So far so good, (i.e. input user_id returns photos from last 30 days, with likes-count and created_time, in a table), until I get to pagination. As expected, I want to hit a 'more' button which loads next json file and adds additional photos to the existing table, but it falls apart there... Here is what I've got, working, except for the pagination attempt.
NOTE: this is an internal app, so the sensitivity of my client_id is not an issue, if it is exposed
<?php
if (!empty($_GET['user_id'])){
$user_id = ($_GET['user_id']);
$instagram_url = 'https://api.instagram.com/v1/users/' . $user_id . '/media/recent/?client_id=MY_CLIENT_ID';
$instagram_json = file_get_contents($instagram_url);
$instagram_array = json_decode($instagram_json, true);
}
?>
...
<?php
if(!empty($instagram_array)){
$instagram_array['pagination'] as $page { // Attempt at pagination
echo '<p>' .$page['next_url'].'</p>'; // Attempt at pagination
} // Attempt at pagination
foreach($instagram_array['data'] as $image){
if ($image['created_time'] > strtotime('-30 days')) {
echo '<tr>';
echo '<td>' . date('M d, Y', $image['created_time']) . '</td>';
echo '<td>'.$image['likes']['count'].'</td>';
echo '<td><img src="'.$image['images']['standard_resolution']['url'].'" alt=""/ style="max-height:40px"></td>';
echo '</tr>';
}
}
}
?>
</body>
</html>
Note: this is cobbled together from a few other sources - I am a total noob, so please forgive me if I need a little hand-holding...:)
You may specify min_timestamp to return medias which taken later than this timestamp
https://api.instagram.com/v1/users/{user_id}/media/recent/?access_token={access_token}&min_timestamp={min_timestamp}
$instagram_array['pagination']['next_url'] should be removed, it may include your access token which is a sensible data, that must be always invisible.
list_ig.php
<?
$user_id = "...";
$access_token = "...";
//30 day ago
$min_timestamp = strtotime("-30 day",time());
//pagination feature
$next_max_id = $_GET['next_max_id'];
$instagram_url = "https://api.instagram.com/v1/users/" . $user_id . "/media/recent/?access_token=" .$access_token. "&min_timestamp=" . $min_timestamp;
if($next_max_id != "")
$instagram_url .= "&max_id=" . $next_max_id;
$instagram_json = file_get_contents($instagram_url);
$instagram_array = json_decode($instagram_json ,true);
?>
<? if( $instagram_array['pagination']['next_max_id'] != "" ): ?>
More
<? endif;?>
.... print instagram data....
Instagram AJAX Demo
http://jsfiddle.net/ajhtLgzc/
Just beginning PHP to bear with me.
Results I'm trying to achiever:
I have a table of YouTube URL's and MetaData.
Trying to build this:
<div class="slide">
<iframe></iframe>
<iframe></iframe>
</div>
<div class="slide">
<iframe></iframe>
<iframe></iframe>
</div>
Two videos per slide, then I'm going to paginate through results using Deck.js.
I suspect I'm going about this completely the wrong way, not that experienced at programmin g logic;
while($data = mysql_fetch_array($result)) {
for ($counter = 1; $counter<=2; $counter++) {
echo "<div class=\"slide\">";
echo "<h3>" . $data['VIDEO_TITLE'] . "</h3>";
echo "<iframe width=\"560\" height=\"315\" src=\"" . $data['VIDEO_URL'] . "\" frameborder=\"0\" allowfullscreen></iframe>";
/* If Video 1, increment counter for 2nd video */
if ($counter == 1) {
$counter++;
}
/* If Video 2, close div and reset counter */
else if ($counter == 2) {
echo "</div>";
$counter = 1;
}
/* If error break out */
else {
echo "</div>";
break;
}
}
}
Basically trying to nest loops to keep track of how many videos per div and start a new one when a div has two.
I've tried a few different ways, this being the latest. Results in:
<div class="slide">
<iframe></iframe>
<div class="slide>
<iframe></iframe>
Hit the blank wall now, not sure what to try next. Willing to use/learn any method to accomplish the results, just not sure where to go at this point.
Cheers.
You could remove the second loop all together using the % operator (modulus). The idea is that a % b === 0 then the number a was evenly divisible by b. Using this, you can easily check for even or odd or every Nth row.
$k = 1;
echo "<div class=\"slide\">";
while($data = mysql_fetch_array($result)) { // you should really change to mysqli or PDO
if($k % 3 === 0){
echo "</div>";
echo "<div class=\"slide\">";
}
echo "<h3>" . $data['VIDEO_TITLE'] . "</h3>";
echo "<iframe width=\"560\" height=\"315\" src=\"" . $data['VIDEO_URL'] . "\" frameborder=\"0\" allowfullscreen></iframe>";
$k++;
}
echo "</div>";
Put the echo <div> before the for loop (still inside the while loop) and the </div> after the for loop
In your while loop you're retrieving just one row, but then you're iterating over it twice with a nested loop. Do away with the inner loop and just use a flip-flop variable to track left and right. I think this will do what you want:
$left=true; // track whether we're emitting HTML for left or right video
while($data = mysql_fetch_array($result)) {
if ($left) {
echo "<div class=\"slide\">";
echo "<h3>" . $data['VIDEO_TITLE'] . "</h3>";
}
echo "<iframe width=\"560\" height=\"315\" src=\"" . $data['VIDEO_URL'] . "\" frameborder=\"0\" allowfullscreen></iframe>";
if (!$left) {
echo "</div>";
}
$left = !$left; // invert $left to indicate we're emitting the right iFrame
}
// end of loop. If we had an odd number of
// videos, tidy up the HTML
if (!$left) {
echo "</div>";
}
PHPFiddle
<?php
$x = 10;
$counter = 0;
while($x > 0)
{
if($counter != 0 && $counter % 2 == 0)
{
echo "ENDOFSLIDE</br>";
}
if($counter == 0 || $counter % 2 == 0)
{
echo "SLIDE</br>";
}
echo "iframe => $x </br>";
$x--;
$counter++;
}
echo "ENDOFSLIDE";
?>
It won't work because the for loop is inside the fetch loop for the SQL data. The second iteration of the for loop does not have a new SQL row. A better solution would be to capture the common column that identifies the two videos (the title) and generate a new div whenever that value changes. Try something like this, which will work for any number of SQL rows with the same title. This will also give proper results if the SQL query returns no rows and will handle the potential of a title with only one URL - which could get ugly if you merely flip-flop and end up with URLs on the wrong title. Of course, as in your current solution, your SQL query must ORDER BY VIDEO_TITLE so the rows are adjacent. I didn't run it, but should be close.
$lastTitle = "";
$n = 0; //count SQL rows processed
while($data = mysql_fetch_array($result)) {
// See if the title changed from last
if( $data['VIDEO_TITLE'] != $lastTitle ) {
// if we processed any rows, must end the current div before starting a new one
if( $n > 0 )
echo "</div>";
echo "<div class=\"slide\">";
echo "<h3>" . $data['VIDEO_TITLE'] . "</h3>";
//save the title as last title
$lastTitle = $data['VIDEO_TITLE'];
}
$n++; //count the SQL row
echo "<iframe width=\"560\" height=\"315\" src=\"" . $data['VIDEO_URL'] . "\" frameborder=\"0\" allowfullscreen></iframe>";
}
if( $n > 0 )
echo "</div>";
So I'm using the following long bit of code to list upcoming events. It asks for the number of days you want to display events for, let's say 10 days, and it groups as many events in those 10 days. I changed the code so there isn't just one header for a given date with multiple events under it, rather than each event date is shown. However it still gives me all the events of the next 10 days. I would like to limit the code so that of the numerous events of the next 10 days it only returns/displays/outputs 6 events.
I'm pretty sure what I need to change is here:
for ($i=0; $i<$days_to_display; $i++)
but the $days_to_display bit makes it tricky.
Any help would be greatly appreciated!
<?php
// List View of Coming Events v .9
// Plug-in for PHPiCalendar 2.0 / 2.1
// developed by Johnathon Wright (my initials # mustmodify.com)
// Original Publication Date: 2005 10 28
// Originally Developed for St. Barnabas Episcopal Church website
// Include this file from your PHP-enabled front page.
// Do something like this:
// <?PHP include 'd:/inetpub/.../phpical/event_list.php';
// DEFINE the base PHPiCalendar directory below.
define('BASE', 'c:/inetpub/ouhsd.k12.ca.us/phpicalendar/');
// create an actual PHPiCalendar instance
require_once(BASE.'functions/ical_parser.php');
require_once(BASE.'functions/list_functions.php');
require_once(BASE.'functions/template.php');
header("Content-Type: text/html; charset=$charset");
// at this point, the calendar has been generated and its data
// is stored in $master_array. Test to ensure that this is working by
// un-commenting the lines below.
/*
echo "<pre>";
print_r($master_array);
echo "</pre>";
*/
// A few settings...
// days_to_display_default should be a positive integer.
$days_to_display_default = 14;
// SHOW PRIVATE EVENTS {TRUE, FALSE}
// In Mozilla Sunbird, events can be set to PRIVATE.
// PHPiCalendar does not display the title or description for
// these events, but does display the time, if applicable.
// If you want to hide these events, set $show_private_events to FALSE.
// Otherwise, it should be TRUE
$show_private_events = TRUE;
// day_to_begin should be a text string. See http://www.php.net/strtotime
// for full documentation. Some values I tested:
// -------------------------------------------------------
// last monday - the most recent Monday.
// thursday - this gave me the date of the next Wednesday.
// yesterday - yesterday
// today - today
// next week - +2 weeks (How can this be? Don't ask me, it's PHP...)
// 1 week - a week from today
$day_to_begin = "today";
// Replace with the commented code if you would NOT like
// users to be able to set this value on their own.
$days_to_display = $days_to_display_default;
/*
// this code replaces the above code if you want to prevent
// users from setting the number of days to display
$days_to_display = $days_to_display_default;
*/
// This next section seems terribly inefficient. We calculate the unix
// timestamp of first-thing-this-morning by finding out the date
// and then looking up the timestamp for that date...
// Again, the commented code prevents users from setting their own start date.
$date_start = date('Ymd', strtotime("now"));
$timestamp_start = strtotime(dateOfWeek($getdate, $date_start));
/*
$date_start = date('Ymd', strtotime("now"));
$timestamp_start = strtotime(dateOfWeek($getdate, $date_start));
*/
// Display the date range for this list
$timestamp_end = $timestamp_start + ($days_to_display * 24 * 60 * 60);
// seed the iterator $thisdate with todays timestamp.
// It will loop through $days_to_display...
$thisdate = $timestamp_start;
// Loop through the days, finding events in each day
for ($i=0; $i<$days_to_display; $i++)
{
$thisday = date("Ymd", $thisdate);
if (isset($master_array[$thisday]))
{
echo "<br/>";
foreach($master_array[($thisday)] as $event_start_time => $event_set)
{
foreach ($event_set as $event_id => $event_info)
{
// Where are we?
// date is $thisdate
// time is $event_start_time
// event is $event_id;
if (! (($event_info['event_text'] == '**PRIVATE**') && ($show_private_events == FALSE)))
{
// event title
echo "<li>";
echo "<span class='bold_text'>" . stripslashes(urldecode($event_info['event_text'])) . "</span><br/>";
// event time range, if not an all-day event
echo " <span style='display: block;'>". date("D. F jS", $thisdate) . "";
if (! (($event_info['event_start'] == '0000') && ($event_info['event_end'] == '0000')))
{
echo ":
" . date("g:ia", $event_info['start_unixtime']) . " - " . date("g:ia", $event_info['end_unixtime'])."</span>";
}
// event location
if (strlen($event_info['location']) > 0)
{
echo " <span class='italic_text'>" . stripslashes(urldecode($event_info['location'])) . "</span>";
}
/*
if ( (($event_info['event_start'] == '0000') && ($event_info['event_end'] == '0000')))
{
echo "all day";
}*/
// event description.
echo "</li>";
} // IF private event AND we don't want to see those
}// END enter this event
} // END foreach event
} // END if there are any events today in the array
// iterator should be the next day.
// Why is this 25? Shouldn't it be 24?
$thisdate = ($thisdate + (25 * 60 * 60));
}
?>
Put a counter in there somewhere to keep track of how many events have been output, and terminate the loop once you reach the limit:
$limit = 6;
$displayed = 0;
foreach(...) {
if (show_event()) {
... show event ...
$displayed++;
if ($displayed >= $limit) {
break;
}
}
}
This may not be the best way! But you could add another for loop above the foreach eg:
for ($i=0; $i<$days_to_display; $i++)
{
$thisday = date("Ymd", $thisdate);
if (isset($master_array[$thisday]))
{
echo "<br/>";
for($k=0;$k<=$noofevents;$k++) //Where $noofevents is the number of events!
{
foreach($master_array[($thisday)] as $event_start_time => $event_set)
{
foreach ($event_set as $event_id => $event_info)
{
// Where are we?
// date is $thisdate
// time is $event_start_time
// event is $event_id;
if (! (($event_info['event_text'] == '**PRIVATE**') && ($show_private_events == FALSE)))
{
// event title
echo "<li>";
echo "<span class='bold_text'>" . stripslashes(urldecode($event_info['event_text'])) . "</span><br/>";
// event time range, if not an all-day event
echo " <span style='display: block;'>". date("D. F jS", $thisdate) . "";
if (! (($event_info['event_start'] == '0000') && ($event_info['event_end'] == '0000')))
{
echo ":
" . date("g:ia", $event_info['start_unixtime']) . " - " . date("g:ia", $event_info['end_unixtime'])."</span>";
}
// event location
if (strlen($event_info['location']) > 0)
{
echo " <span class='italic_text'>" . stripslashes(urldecode($event_info['location'])) . "</span>";
}
/*
if ( (($event_info['event_start'] == '0000') && ($event_info['event_end'] == '0000')))
{
echo "all day";
}*/
// event description.
echo "</li>";
} // IF private event AND we don't want to see those
}// END enter this event
} // END foreach event
} // END for x events
} //END if isset
}//END for days
I am using the following code:
$result = mysql_query("SELECT * FROM table LEFT JOIN table2
ON table.field = table2.field WHERE ( table.field = '$pid' )
AND ( table.field5 LIKE '%$q%' OR table.field3 LIKE '%$q%'
OR table2.field2 LIKE '%$q%' )");
if (empty($what)) {
$countpls = "0";
} else {
$countpls = mysql_num_rows($result);
}
<?php
if ($countpls > 10) {
echo '<a id=pgnvg href="' . $_SERVER['PHP_SELF'] . '?pg=' . ($startrow + 20) . '&q=' . ($what) . '">Next</a>';
} else {
echo "";
}
$prev = $startrow - 20;
//only print a "Previous" link if a "Next" was clicked
if ($prev >= 0) {
echo '<a id=pgnvg2 href="' . $_SERVER['PHP_SELF'] . '?pg=' . $prev . '&q=' . ($what) . '">Previous</a>';
} else {
echo "";
}
?>
I want the next to show only if there are more entries to show and previous only if there are more entries to circle back to. It works on the first page bt then on the last page Next shows despite teh fact that there are no more results to show.
I tried adding the 'else' but its still not working.
Any ideas?
if($countpls > 0){
$pg = $_POST['pg']?$_POST['pg']:1;
//if it's not the first page...
if($pg>1){
echo '<a id="pgnvg" href="'.$_SERVER['PHP_SELF'].'?pg='.($pg-1).'&q='.$what.'">Previous</a>';
}
//if you have more registers to show...
if(($countpls-(($pg-1)*10))>10){
echo '<a id="pgnvg" href="'.$_SERVER['PHP_SELF'].'?pg='.($pg+1).'&q='.$what.'">Next</a>';
}
}
In order to calculate your offset to use in queries, use this:
$offset = ($_POST['pg']-1)*10;
It would help if you would provide the code that's setting $countpls. That might be the part that's causing the problem. Also, the else's are unnecessary. However, try this:
if($countpls - $startrow > 20)
{
echo '<a id=pgnvg href="'.$_SERVER['PHP_SELF'].'?pg='.($startrow+20).'&q='.($what).'">Next</a>';
}
I think it would do you good if you followed a tutorial to grasp the basic concepts. It even comes with the example that could either 1.) replace your current pagination or 2.) fix it.
http://www.phpfreaks.com/tutorial/basic-pagination