PHP pick tweets code - php

I have a php code that fetches my latest tweet and displays it on my website. It works great but I would like to know if I could do this but maybe fetching my 5 last tweets instead of only the latest. This is my code for twitter.php:
function returnTweet()
{
$username = "username";
$prefix = "<div><big><i>#$username ";
$suffix = "</i></big></div>";
$feed = "http://search.twitter.com/search.atom?q=from:" . $username . "&rpp=5";
$twitterFeed = file_get_contents($feed);
$tweet = parse_feed($twitterFeed);
return $prefix.$tweet.$suffix;
}
function parse_feed($feed)
{
$stepOne = explode("<content type=\"html\">", $feed);
$stepTwo = explode("</content>", $stepOne[1]);
$tweet = $stepTwo[0];
$tweet = str_replace("<", "<", $tweet);
$tweet = str_replace(">", ">", $tweet);
return $tweet;
}
And i display it in my php page like this:
include "twitter.php";
echo "".returnTweet();
Would appreciate any help in this!
Regards from Paparappa

You're much better off using an XML-parser for this (for example: http://www.php.net/manual/en/simplexml.examples-basic.php).
(not sure about the structure of twitter-atoms, so $xml->tweet[$i] is probably something else..)
$xml = new SimpleXMLElement($twitterFeed);
$tweets = array();
for ($i = 0; $i < 5; $i++) {
$tweets[] = $xml->tweet[$i];
}

Related

the web page is temporarily down or it may have moved permanently to another address. ERR_RESPONSE_HEADERS_TRUNCATED

I'm trying to get an RSS feed, I remove all stopwords, stemm... but it works sometimes. I do not know what is happening. Could anyone see my code and tell me where is the error?. Please
functions.php
<?php
include ("stemm_es.php");
function quitarAcento($incoming_string){
$tofind = "ÀÁÂÄÅàáâäÒÓÔÖòóôöÈÉÊËèéêëÇçÌÍÎÏìíîïÙÚÛÜùúûüÿÑñ";
$replac = "AAAAAaaaaOOOOooooEEEEeeeeCcIIIIiiiiUUUUuuuuyNn";
return utf8_encode(strtr(utf8_decode($incoming_string),
utf8_decode($tofind),
$replac));
}
function limpiar($String){
$String = str_replace(array('á','à','â','ã','ª','ä'),"a",$String);
$String = str_replace(array('Á','À','Â','Ã','Ä'),"A",$String);
$String = str_replace(array('Í','Ì','Î','Ï'),"I",$String);
$String = str_replace(array('í','ì','î','ï'),"i",$String);
$String = str_replace(array('é','è','ê','ë'),"e",$String);
$String = str_replace(array('É','È','Ê','Ë'),"E",$String);
$String = str_replace(array('ó','ò','ô','õ','ö','º'),"o",$String);
$String = str_replace(array('Ó','Ò','Ô','Õ','Ö'),"O",$String);
$String = str_replace(array('ú','ù','û','ü'),"u",$String);
$String = str_replace(array('Ú','Ù','Û','Ü'),"U",$String);
$String = str_replace(array('[','^','´','`','¨','~',']','"',"'",'(',')','{','}',',','.',':',';','%','-',
'#','#','|','!','·','$','&','/','?','¡','¿','+', '”', '“', '’', '‘'),"",$String);
$String = str_replace("ç","c",$String);
$String = str_replace("Ç","C",$String);
$String = str_replace("ñ","n",$String);
$String = str_replace("Ñ","N",$String);
$String = str_replace("Ý","Y",$String);
$String = str_replace("ý","y",$String);
$String = str_replace("á","a",$String);
$String = str_replace("Á","A",$String);
$String = str_replace("é","e",$String);
$String = str_replace("É","E",$String);
$String = str_replace("í","i",$String);
$String = str_replace("Í","I",$String);
$String = str_replace("ó","o",$String);
$String = str_replace("Ó","O",$String);
$String = str_replace("ú","u",$String);
$String = str_replace("Ú","U",$String);
return $String;
}
function getFeed($feed_url) {
$x = simplexml_load_string(file_get_contents($feed_url));
$stopwords = file_get_contents('stopword.txt');
$stopwords = explode(" ", $stopwords);
$t=0;
foreach($x->channel->item as $entry){
$t++;
$title = trim( strip_tags( mb_strtolower( limpiar($entry->title) ) ) );
$description = trim( strip_tags( mb_strtolower( limpiar($entry->description) ) ) );
$title = explode(" ", $title);
$description = explode(" ", $description);
for($j = 0; $j < count($title); $j++){
if($title[$j] != ""){
for($i = 0; $i < count($stopwords); $i++){
if($stopwords[$i] != ""){
$title[$j] = preg_replace("/\b$stopwords[$i]\b/i", " ", $title[$j]);
$title[$j] = stemm_es::stemm($title[$j]);
}
}
}
}
for($j = 0; $j < count($description); $j++){
if($description[$j] != ""){
for($i = 0; $i < count($stopwords); $i++){
if($stopwords[$i] != ""){
$description[$j] = preg_replace("/\b$stopwords[$i]\b/i", " ", $description[$j]);
$description[$j] = stemm_es::stemm($description[$j]);
}
}
}
}
print_r($title);
print_r($description);
}
}
?>
index.php
<!DOCTYPE html>
<html class="no-js" lang="es">
<head>
<meta charset="utf-8">
<title>Inicio | Investigador</title>
</head>
<body>
<?php require "functions.php"; ?>
<?php
$feed = "http://ep00.epimg.net/rss/ccaa/valencia.xml";
if ($feed != "") {
getFeed(feed);
}
?>
</body>
</html>
We've had this issue arise for some users with a recent release. Not sure if it is us or timing with Chrome .
It is only affecting some users, and only in Chrome, and clearing cache has helped most users but not all.
Still searching for a definitely solution to it.
EDIT:
After a looooong time I actually resolved it for me by updating the session config settings in CodeIgniter.
I had to update:
$config['sess_encrypt_cookie'] = FALSE;
to:
$config['sess_encrypt_cookie'] = TRUE;
What was happening was on first login, it would work fine, but the second login was getting some sort of conflict with the cookie.
I didn't find out exactly what the issue was, but this seems to be a Chrome based bug a few people have had over the years, but there's not much around on it.

how to find out keyword position on google with php

How can I find out my keyword position on Google with PHP ?
I tried this URL :
http://www.google.com/url?sa=t&source=web&ct=res&cd=7&url=http%3A%2F%2Fwww.example.com%2Fmypage.htm&ei=0SjdSa-1N5O8M_qW8dQN&rct=j&q=flowers&usg=AFQjCNHJXSUh7Vw7oubPaO3tZOzz-F-u_w&sig2=X8uCFh6IoPtnwmvGMULQfw
but I couldn't get any html source code.
How can I do this ?
I use this script I made.
As it relies on possibly changing html from google it is not reliable but does it's job for now :
<?php
// Include the phpQuery library
// Download at http://code.google.com/p/phpquery/
include("phpQuery-onefile.php");
$country = "en";
$domain = "stackoverflow.com";
$keywords = "php google keyword rank checker";
$firstnresults = 50;
$rank = 0;
$urls = Array();
$pages = ceil($firstnresults / 10);
for($p = 0; $p < $pages; $p++){
$start = $p * 10;
$baseurl = "https://www.google.com/search?hl=".$country."&output=search&start=".$start."&q=".urlencode($keywords);
$html = file_get_contents($baseurl);
$doc = phpQuery::newDocument($html);
foreach($doc['#ires cite'] as $node){
$rank++;
$url = $node->nodeValue;
$urls[] = "[".$rank."] => ".$url;
if(stripos($url, $domain) !== false){
break(2);
}
}
}
print "Country: ".$country."\n";
print "Domain: ".$domain."\n";
print "Keywords: ".$keywords."\n";
print "Rank: ".$rank."\n";
print "First urls:\n";
print implode("\n", $urls)."\n";
?>
Maybe you should just use a class written for this purpose, for example this one on github

Undefined variable on php script

I am getting notice on line 30 that twetout is undefined variable
<?php
$username = "tomaskutaj";/*
$limit = 5;
$feed = 'http://twitter.com/statuses/user_timeline.rss?screen_name='.$username.'&count='.$limit;*/
$feed ="http://search.twitter.com/search.rss?q=#tomaskutaj";
$tweets = file_get_contents($feed);
$tweets = str_replace("&", "&", $tweets);
$tweets = str_replace("<", "<", $tweets);
$tweets = str_replace(">", ">", $tweets);
$tweet = explode("<item>", $tweets);
$tcount = count($tweet) - 1;
for ($i = 1; $i <= $tcount; $i++) {
$endtweet = explode("</item>", $tweet[$i]);
$title = explode("<title>", $endtweet[0]);
$content = explode("</title>", $title[1]);
$content[0] = str_replace("–", "—", $content[0]);
$content[0] = preg_replace("/(http:\/\/|(www\.))(([^\s<]{4,68})[^\s<]*)/", '$1$2$4', $content[0]);
$content[0] = str_replace("$username: ", "", $content[0]);
$content[0] = preg_replace("/#(\w+)/", "#\\1", $content[0]);
$content[0] = preg_replace("/#(\w+)/", "#\\1", $content[0]);
$mytweets[] = $content[0];
}
$x=1;
while (list(, $v) = each($mytweets)) {
$tweetout .= "<div>$v</div>\n";
if ($x==1){
$first=$tweetout;
};
$x++;
}
if ((strstr($first,'#tomaskutaj'))&&(strstr($first,'#tomaskutaj')))
echo($first);
?>
But after I added before last while saying '$tweetout='';' it runs the script but doesnt get any output and no error either, where is the problem?
The problem is that you are trying to append to a variable that is not defined.
$tweetout .= "<div>$v</div>\n";
PHP gives you a notice, as in most cases, this happens because you typo-ed a variable name. You don't get any errors, as PHP just assumes you meant to append to null and continues.
To resolve the issue, before your while loop, define $tweetout:
$tweetout = '';
You should definitely add a
$tweetout = "";
before your loop, appending to a non existing string is an error.
The reason you're getting nothing on the screen is that $first does not contain #tomaskutaj, and the if-statement at the end requires that (and #tomaskutaj which is there) to print anything.

Getting last tweet with PHP

To get my last tweet in PHP I use this code :
function getTweets($tweetsToDisplay, $user_id) {
$twitterrequest = 'http://api.twitter.com/1/statuses/user_timeline.json?user_id=' . $user_id . '&include_rts=true&count=' . $tweetsToDisplay;
$twitterci = curl_init($twitterrequest);
curl_setopt($twitterci, CURLOPT_RETURNTRANSFER, TRUE);
$twitterinput = curl_exec($twitterci);
curl_close($twitterci);
return ($twitterinput);
}
$user_id = '99999999';
$var = json_decode(getTweets(1, $user_id));
$txt = $var[0]->text;
$txt = preg_replace('%(https?://)[^\s]*%', '$1...', $txt);
echo $txt;
Works fine but I want to get the date as well. How to extract it ?
I hope code below help you.
function getTimeline($count, $username) {
$url = 'http://api.twitter.com/1/statuses/user_timeline.json?screen_name='.$username.'&count=.'$count;
$tweets = json_decode(file_get_contents($url),TRUE);
return $tweets;
}
You can try this simple PHP function that I created to catch latest tweets easily (does not require API authentication). Must be optimized :)
function getTweets($user, $count) {
$datas = file_get_contents('https://twitter.com/'.$user);
preg_match_all('/<p class="js-tweet-text tweet-text">(.*?)<\/p>/', $datas, $matchetweets);
$matchetweets[1] = preg_replace('/<s>(.?)<\/s>/', '$1', $matchetweets[1]);
$matchetweets[1] = preg_replace('/(class|dir|rel|data-expanded-url|data-pre-embedded|data-query-source)="(.*?)"/', '', $matchetweets[1]);
$matchetweets[1] = preg_replace('!\s+!', ' ', $matchetweets[1]);
for ($i = 1; $i <= $count; $i++) {
echo '<li>'.$matchetweets[1][$i].'</li>'."\n";
}
};
Usage
echo getTweets('nasa', 3);
UPDATE (10/15/2014) :
This version is out of date and not working anymore. Here is an updated PHP code to parse tweets easily.
function getTweets($user, $count) {
$datas = file_get_contents('https://mobile.twitter.com/'.$user);
preg_match_all('/<div class="tweet-text" data-id="\d*">(.*?)<\/div>/', $datas, $matchetweets);
$matchetweets[1] = preg_replace('/<div class="dir-ltr" dir="ltr">/', '', $matchetweets[1]);
for ($i = 1; $i <= $count; $i++) {
echo '<li>'.$matchetweets[1][$i].'</li>'."\n";
}
};
UPDATE (5/30/2015) :
function getTweets($user, $count) {
$datas = file_get_contents('https://mobile.twitter.com/'.$user);
preg_match_all('/<div class="tweet-text" data-id="\d*">(.*?)<\/div>/s', $datas, $matchetweets, PREG_SET_ORDER);
for ($i = 1; $i <= $count; $i++) {
$matchetweets[$i][0] = preg_replace('/<div class="dir-ltr" dir="ltr">/', '', $matchetweets[$i][0]);
$matchetweets[$i][0] = preg_replace('/\s+/', ' ', $matchetweets[$i][0]);
$matchetweets[$i][0] = str_replace('"> ', '">', $matchetweets[$i][0]);
echo '<li>'.$matchetweets[$i][0].'</li>'."\n";
}
};
Usage doesn't change. Minimum 1 tweet, maximum 20 tweets.
<?php
$date = $var[0]->created_at;
That should work!
Add this to bottom of your code.
$time = $var[0]->created_at;
echo $time;
Based on the Twitter API results from http://dev.twitter.com/doc/get/statuses/user_timeline, it appears that you could use the created_at param.
You have:
$txt = $var[0]->text;
If that works then add
$created = $vars[0]->created_at;
echo $txt;
echo "<span>".$created."</span>" ;

How to convert URL string with multiple delimiters into another string in PHP?

So I have this sample string:
?items=3744130|1^356221|2^356222|1
extracted from a URL:
http://www.example.com/process.php?items=3744130|1^356221|2^356222|1
I need to convert it into this, and for the life of me I'm getting stuck.
?items=model_1=3744130&qty_1=1&model_2=356221&qty_2=2&model_3=356222&qty_3=1
I've gotten this far but that's it.
$url = substr($_SERVER['QUERY_STRING'],6);
$query = explode('^', $url);
echo http_build_query($query, 'model_');
Output currently is:
model_0=1234435%7C9&model_1=56788%7C9&model_2=6758765%7C9&model_3=3736543%7C9
How can I get the first set to be model_1 instead of the default model_0?
Thanks
You need to build the array with keys before passing it to http_build_query() if you want the numbering to start with 1.
$arr = array();
$count = 1;
foreach (explode('|', $_GET['items']) as $item) {
$elements = explode('^', $item);
if (count($elements) == 1) {
$arr["model_$count"] = $elements[0];
$arr["qty_$count"] = 1;
}
else {
$arr["model_$count"] = $elements[1];
$arr["qty_$count"] = $elements[0];
}
$count++;
}
$query = http_build_query($arr);
A quick patch should be
....
$url = substr($_SERVER['QUERY_STRING'],6);
$query = explode('^', $url);
array_unshift($query,'placeholder');
$result=http_build_query($query, 'model_');
$result = substr($result, 19);
....
Try this:
$items = explode('^', $_GET['items']);
$query = '';
foreach ($items as $key => $val) {
list($model, $qty) = explode('|', $val);
$query .= '&model_'.($key+1).'='.urlencode($model);
$query .= '&qty_'.($key+1).'='.urlencode($qty);
}
echo substr($query, 1);

Categories