Getting last tweet with PHP - 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>" ;

Related

How can I remove random amount of dots and get the last number?

I'm trying to strip all the dots and then get the number, and NAME[X] as an output.
My output is:
NAME..................................................................................................3
NAME2...................................................................................................24
NAME3...............................................................................................................................................5
NAME4.......................347
NAME5............................................................................................7
NAME6......................................................................9
I've tried something like this so far:
function introExcerpt($id = null, $introExcerptCut = null)
{
$fileInfo['intro'] = 'my string';
$introExcerpt = trim($fileInfo['intro']);
$lines = preg_split('/\r\n|\r|\n/', $introExcerpt);
$intro = '<div class="toc"><ul class="toc">';
for ($i = 0; $i < count($lines); $i++) {
// if (isset($lines[$i]) && substr(trim($lines[$i]), -1) !== '.') {
$intro.= $lines[$i].'<br />';
//}
}
$intro .= '</div></ul>';
return $intro;
}
Not sure exactly what your output should look like, but you may try just running preg_replace directly on the variable containing all lines:
$lines = preg_replace("/(NAME\d+)\.+(\d+)/", "$1[$2]", $lines);
This would generate the following output based on your sample input:
NAME[3]
NAME2[24]
NAME3[5]
NAME4[347]
NAME5[7]
NAME6[9]
You can use the following function:
function introExcerpt($str, $id = null, $introExcerptCut = null)
{
$fileInfo['intro'] = $str;
$introExcerpt = trim($fileInfo['intro']);
$lines = preg_split('/\r\n|\r|\n/', $introExcerpt);
$intro = '<div class="toc"><ul class="toc">';
for ($i = 0; $i < count($lines); $i++) {
$intro .= '<li>';
$tmpLineArray = explode('.', $lines[$i]);
array_filter($tmpLineArray, function ($value) {
return !is_null($value) && $value != '';
});
foreach ($tmpLineArray as $value) {
$intro .= $value . ' ';
}
$intro .= '</li>';
}
$intro .= '</ul></div>';
return $intro;
}
It is splitting the entire row into array using dot as separator and filters out the empty elements.

php array keep pushing in the depth

My current code is like :
<?php
$item = "123.456.789.963.852.741";
$item_arr = explode(".", $item);
$inner_count = count($item_arr);
$parent_element = "myarray";
if($inner_count==3){
$my_array[$item_arr[0]]['XYZ-Key'][$item_arr[1]]['XYZ-Key'][$item_arr[2]]['order'] = $count;
$my_array[$parent_element]['XYZ-Key'][$item_arr[1]]['XYZ-Key'][$item_arr[2]]=$my_array[$item_arr[0]]['XYZ-Key'][$item_arr[1]]['XYZ-Key'][$item_arr[2]];
unset($my_array[$item_arr[0]]['XYZ-Key'][$item_arr[1]]['XYZ-Key'][$item_arr[2]]);
}
if($inner_count==4){
$my_array[$item_arr[0]]['XYZ-Key'][$item_arr[1]]['XYZ-Key'][$item_arr[2]]['XYZ-Key'][$item_arr[3]]['order'] = $count;
$my_array[$parent_element]['XYZ-Key'][$item_arr[1]]['XYZ-Key'][$item_arr[2]]['XYZ-Key'][$item_arr[3]]=$my_array[$item_arr[0]]['XYZ-Key'][$item_arr[1]]['XYZ-Key'][$item_arr[2]]['XYZ-Key'][$item_arr[3]];
unset($my_array[$item_arr[0]]['XYZ-Key'][$item_arr[1]]['XYZ-Key'][$item_arr[2]]['XYZ-Key'][$item_arr[3]]);
}
if($inner_count==5){
$my_array[$item_arr[0]]['XYZ-Key'][$item_arr[1]]['XYZ-Key'][$item_arr[2]]['XYZ-Key'][$item_arr[3]]['XYZ-Key'][$item_arr[4]]['order'] = $count;
$my_array[$parent_element]['XYZ-Key'][$item_arr[1]]['XYZ-Key'][$item_arr[2]]['XYZ-Key'][$item_arr[3]]['XYZ-Key'][$item_arr[4]]=$my_array[$item_arr[0]]['XYZ-Key'][$item_arr[1]]['XYZ-Key'][$item_arr[2]]['XYZ-Key'][$item_arr[3]]['XYZ-Key'][$item_arr[4]];
unset($my_array[$item_arr[0]]['XYZ-Key'][$item_arr[1]]['XYZ-Key'][$item_arr[2]]['XYZ-Key'][$item_arr[3]]['XYZ-Key'][$item_arr[4]]);
}
now i want to extend it to more count (right now code is up to 5)
but the problem I can not the code in the same way
You can do it in this manner. Just change string for your format
$item = "1.2.3.4.5";
$ar = explode('.', $item);
$start = '{';
$end = '}';
foreach($ar as $i) {
$start .= '"'.$i.'":{';
$end = '}'.$end;
}
$temp = $start . '"order":{}' .$end; // {"1":{"2":{"3":...{"order":{}}}}}
$res = json_decode($temp,true);

PHP strings concatenation

My code cycles through a CSV file, converting it to XML:
<?php
for ($i = 1; $i < $arraySize; $i++) {
$n = 0;
if (substr($csv[$i][0], 0, 1) == $let) {
$surName = $dom->createElement('name');
$name = $csv[$i][0];
$nameText = $dom->createTextNode($name);
$surName->appendChild($nameText);
$text = str_replace(chr(94), ",", $csv[$i][4]);
$n = $i + 1;
$next = $csv[$n][0];
while ($next == 'NULL') {
$repl = str_replace(chr(94), ",", $csv[$n][4]);
$text = $repl;
$n++;
$next = $csv[$n][0];
}
$bio = $dom->createElement('bio');
$bioText = $dom->createTextNode($text);
$bio->appendChild($bioText);
$person = $dom->createElement('person');
$person->appendChild($surName);
$person->appendChild($bio);
$people->appendChild($person);
}
}
$xmlString = $dom->saveXML();
echo $xmlString;
?>
The problem is the $text = $repl; Typing $text .= $repl; brings:
error on line 1 at column 1: Document is empty.
but omitting the . just gives the last line of text.
the backup code works:
public function test($let){
$csv = $this->readCSV("data\AlphaIndex1M.csv");
$arraySize=sizeof($csv);
$let = strtoupper($let);
//echo '';
for($i=1; $i
echo $csv[$i][0];// .'
echo ', -->'.$csv[$i][4];
$n = $i+1;
$next = $csv[$n][0];
//if($next == 'NULL'){ }
while($next == 'NULL'){
echo $csv[$n][4]. " ";
$n++;
$next=$csv[$n][0];
}
//echo ''
echo '';
}
}
//echo ''
}
You have to initialize your $text before you can append stuff!
So write this before you use it:
$test = "";
(before the while loop or even before the for loop if you want all to be appended)

Getting custom replace to work similar to how PHP PDO works

I just want to know how to replace a certain index character with an array constantly like how PDO works in PHP? Here is my code;
The the code
private $string;
public function __construct($string = null) {
if ($string !== null) {
$this->string = $string;
} else {
$this->string = '';
}
}
public function getString() {
return $this->string;
}
public function replaceWith($index, $array = array()) {
$lastArrayPoint = 0;
$i = 0;
while ($i < sizeof($this->string)) {
if (substr($this->string, $i, $i + 1) == $index) {
$newString[$i] = $array[$lastArrayPoint];
$i = $i . sizeof($array[$lastArrayPoint]);
$lastArrayPoint++;
} else {
$newString[$i] = $this->string[$i];
}
$i++;
}
return $this;
}
and the executing code
$string = new CustomString("if ? == true then do ?");
$string->replaceWith('?', array("mango", "print MANGO"));
echo '<li><pre>' . $string->getString() . '</pre></li>';
Thank you for the help I hope I will recieve.
$string = "if %s == true then do %s. Escaping %% is out of the box.";
$string = vsprintf($string, array("mango", "print MANGO"));
echo "<li><pre>$string</pre></li>";
str_replace has an optional count parameter, so you can make it replace one occurrance at a time. You can just loop through the array, and replace the next question mark for element N.
$string = "if %s == true then do %s";
$params = array("mango", "print MANGO");
foreach ($params as $param)
$string = str_replace('?', $param, $string, 1);
Thanks for the help guys but they did not work the way I wanted it to work. I have found a way to get it too work. Here is the code
public function replaceWith($index, $array = array()) {
$arrayPoint = 0;
$i = 0;
$newString = "";
while ($i < strlen($this->string)) {
if (substr($this->string, $i, 1) === $index) {
$newString .= $array[$arrayPoint];
$arrayPoint++;
} else {
$newString .= substr($this->string, $i, 1);
}
$i++;
}
$this->string = $newString;
return $this;
}
if anyone has a better way then you can tell me but for now this works.

PHP script adding a space in between every character

I have a little problem with a script I wrote.
It basically combines permutations of text in every possible order.
For some reason it is adding a space in between every character - can anyone figure out why?
Thanks in advance.
<?php
if(isset($_POST['submit']))
{
//pull in the perms
$perms = "{#A#B#C|#A#B#D|#A#B#E|#A#B#F|#A#C#D|#A#C#E|#A#C#F|#A#D#E|#A#D#F|#A#E#F|#B#C#D|#B#C#E|#B#C#F|#B#D#E|#B#D#F|#B#E#F|#C#D#E|#C#D#F|#C#E#F|#D#E#F}";
//open the box's
$box1= fopen("box1.txt","r");
$box2= fopen("box2.txt","r");
$box3= fopen("box3.txt","r");
$box4= fopen("box4.txt","r");
$box5= fopen("box5.txt","r");
$box6= fopen("box6.txt","r");
//this is the output
$tulis = fopen("output.txt","w+");
//read the box's
$box1 = fread($box1, filesize("box1.txt"));
$box2 = fread($box2, filesize("box2.txt"));
$box3 = fread($box3, filesize("box3.txt"));
$box4 = fread($box4, filesize("box4.txt"));
$box5 = fread($box5, filesize("box5.txt"));
$box6 = fread($box6, filesize("box6.txt"));
$perms = str_replace("#A","$box1",$perms);
$perms = str_replace("#B","$box2",$perms);
$perms = str_replace("#C","$box3",$perms);
$perms = str_replace("#D","$box4",$perms);
$perms = str_replace("#E","$box5",$perms);
$perms = str_replace("#F","$box6",$perms);
echo $text;
fwrite($tulis,$perms);
//close them properly
$box1= fopen("box1.txt","r");
$box2= fopen("box2.txt","r");
$box3= fopen("box3.txt","r");
$box4= fopen("box4.txt","r");
$box5= fopen("box5.txt","r");
$box6= fopen("box6.txt","r");
fclose($box1);
fclose($box2);
fclose($box3);
fclose($box4);
fclose($box5);
fclose($box6);
fclose($tulis);
}
//this means that if the submit button hasn't been pressed, print the form!
else
{
print '
<form action="'.$_SERVER['PHP_SELF'].'" method="POST">
<input type="submit" name="submit"></input>
</form>
';
}
?>
Unless I am mistaking and I missed what you are trying to do, this script is doing pretty much like what you wrote, except that there are no str_replace and it creates permuations automatically for the number of files you provide (at least 3 for it to work properly) :
$files = array(
"box1.txt",
"box2.txt",
"box3.txt",
"box4.txt",
"box5.txt",
"box6.txt"
);
$contents = array();
foreach ($files as $index => $filename) {
$contents[$index] = trim(file_get_contents($filename), " \n\r");
}
$perms = array();
$len = count($contents);
for ($i=0; $i<$len-2; $i++) {
for ($j=$i+1; $j<$len-1; $j++) {
for ($k=$j+1; $k<$len; $k++) {
$perms[] = $contents[$i] . $contents[$j] . $contents[$k];
}
}
}
$text = '{' . implode('|', $perms) . '}';
file_put_contents('output.txt', $text);
Note that this version does not use fopen and trim the text read from the files to remove any whitespaces (CR and CL characters too) from the content.
** Edit **
This is the actual test program that I have made :
header('Content-type: text/plain; charset=utf-8');
$contents = array(
'A', 'B', 'C', 'D', 'E', 'F'
);
// fixed embedded loops method
$perms = array();
$len = count($contents);
for ($i=0; $i<$len-2; $i++) {
for ($j=$i+1; $j<$len-1; $j++) {
for ($k=$j+1; $k<$len; $k++) {
$perms[] = $contents[$i] . $contents[$j] . $contents[$k];
}
}
}
$text = '{' . implode('|', $perms) . '}';
echo $text . "\n";
// Recursive method
function permutationRecursive( & $perms, $maxDepth, $contents = array(), $values = array(), $startIndex = 0) {
for ($i=$startIndex, $count=count($contents)-($maxDepth-1); $i<$count; $i++) {
array_push($values, $contents[$i]);
if ($maxDepth > 1) {
permutationRecursive( $perms, $maxDepth - 1, $contents, $values, $i + 1);
} else {
$perms[] = implode($values);
}
array_pop($values);
}
}
$perms = array();
permutationRecursive($perms, 3, $contents);
$text = '{' . implode('|', $perms) . '}';
echo $text . "\n";;
The output of this script is
{ABC|ABD|ABE|ABF|ACD|ACE|ACF|ADE|ADF|AEF|BCD|BCE|BCF|BDE|BDF|BEF|CDE|CDF|CEF|DEF}
{ABC|ABD|ABE|ABF|ACD|ACE|ACF|ADE|ADF|AEF|BCD|BCE|BCF|BDE|BDF|BEF|CDE|CDF|CEF|DEF}

Categories