Need to validate "last tweet" script - php

Have been searching for a solution for hours.
My entire WordPress theme validates, except this script I'm using to receive the last tweet:
<?php
$twitterUsername = get_option('of_twitter_username');
$username = $twitterUsername; // Your twitter username.
$prefix = ""; // Prefix - some text you want displayed before your latest tweet.
$suffix = ""; // Suffix - some text you want display after your latest tweet.
$feed = "http://search.twitter.com/search.atom?q=from:" . $username . "&rpp=1";
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;
}
$twitterFeed = file_get_contents($feed);
echo stripslashes($prefix) . parse_feed($twitterFeed) . stripslashes($suffix);
?>
The error, it seems, is:
$tweet = str_replace(">", ">", $tweet);
Not sure how to fix this.
Thanks for any help.

Replace the two str_replace calls with:
$tweet = html_entity_decode($tweet);

Maybe a simplier way (you don't need to parse) is to load http://search.twitter.com/search.json?q=from:the_username and make a json_decode of the result.
Then you can get the last tweet easily.

Related

coordinates function sometimes not working

I'm using this function to get the coordinates of any address:
function getCoordinates($address) {
$address = str_replace(" ", "+", $address); // replace all the white space with "+" sign to match with google search pattern
$address = str_replace("-", "+", $address); // replace all the "-" with "+" sign to match with google search pattern
$url = "http://maps.google.com/maps/api/geocode/json?address=$address";
$response = file_get_contents($url);
$json = json_decode($response,TRUE); //generate array object from the response from the web
return ($json['results'][0]['geometry']['location']['lat'].",".$json['results'][0]['geometry']['location']['lng']);
}
Sometimes it works and sometimes it only gets "," for the same address.
Do I need to use another function?
try this
$url = "http://maps.google.com/maps/api/geocode/json?address=".$address;

Do multiple search and replaces in PHP string?

I am working with PHP and WordPress right now, I need to basically run the below code to Replace text in $current_path with the text in $new_path if $current_path EXIST in $content
I would prefer to be able to iterate over an array instead of running this over and over like this, or any better method would be nice?
$content = 'www.domain.com/news-tag/newstaghere'
$current_path = 'test-tag';
$new_path = 'test/tag';
$content = str_replace($current_path, $new_path, $content);
$current_path = 'news-tag';
$new_path = 'news/tag';
$content = str_replace($current_path, $new_path, $content);
$current_path = 'ppc-tag';
$new_path = 'ppc/tag';
$content = str_replace($current_path, $new_path, $content);
str_replace() accepts array arguments:
$current_paths = array('test-tag','news-tag','ppc-tag');
$new_paths = array('test/tag','news/tag','ppc/tag');
$new_content = str_replace($current_paths, $new_paths, $content);
Or you can use a single array with strtr():
$path_map = array('test-tag'=>'test/tag', 'news-tag'=>'news/tag', 'ppc-tag'=>'ppc/tag');
$new_content = strtr($content, $path_map);
However, you seem to be doing something very generic. Maybe all you need is a regex?
$new_content = preg_replace('/(test|news|ppc)-(tag)/u', '\1/\2', $content);
Or maybe even just
$new_content = preg_replace('/(\w+)-(tag)/u', '\1/\2', $content);
$content = 'www.domain.com/news-tag/newstaghere'
$current_paths = array('test-tag','news-tag','ppc-tag');
$new_paths = array('test/tag','news/tag','ppc/tag';
$content = str_replace($current_paths, $new_paths, $content);
Array arguments can be provided for the str_replace function, as noted on the following PHP.net page:
http://php.net/manual/en/function.str-replace.php
Please see "Example #2" on the page linked above for details.
You can do that:
$content = 'www.domain.com/news-tag/newstaghere';
$content = preg_replace('~www\.domain\.com/\w++\K-(?=tag/)~', '/', $content);

Getting error in Amazon product API sample code (PHP)

I downloaded Product Advertising PHP Soap Library and was going through the sample codes. I configured the value of 'AWS_API_KEY', 'AWS_API_SECRET_KEY', 'AWS_ASSOCIATE_TAG', 'AWS_ANOTHER_ASSOCIATE_TAG' in sampleSettings.php file. I'm getting the below mentioned error in my browser while trying to access 'sampleItemSearch.php'.
SOAP-ERROR: Parsing WSDL: Couldn't load from 'http://webservices.amazon.com/AWSECommerceService/AWSECommerceService.wsdl' : Start tag expected, '<' not found
I tried to take help help from Link: https://forums.aws.amazon.com/thread.jspa?messageID=270273 but it did not work.
Note: I have tried to run the below url in browser and got the following output:
$request="http://webservices.amazon.com/onca/xml?Service=AWSECommerceService&AssociateTag=ASSOCIATETAG01-20&AWSAccessKeyId=MY_ACCESS_KEY_ID&Operation=ItemSearch&Version=2011-08-01&SearchIndex=Books&Keywords=harry%20potter&Timestamp=2013-04-10T12%3A44%3A42.000Z&Signature=ASasd5645AdSG878asdHsaHJ9YTefl1F6i0%3D";
Please suggest what I should do.
I solved it at last. Below mentioned code is working fine.
AWSAccessKeyId = "*******************";
$SecretAccessKey = "******************************";
$AssociateTag = "***************";
$ItemId = '****'; //10 or 13 digit isbn
$Timestamp = gmdate("Y-m-d\TH:i:s\Z");
$Timestamp = str_replace(":", "%3A", $Timestamp);
$ResponseGroup = "ItemAttributes,Images";
$ResponseGroup = str_replace(",", "%2C", $ResponseGroup);
$String = "AWSAccessKeyId=$AWSAccessKeyId&AssociateTag=$AssociateTag&IdType=ISBN&ItemId=$ItemId&Operation=ItemLookup&ResponseGroup=$ResponseGroup&SearchIndex=Books&Service=AWSECommerceService&Timestamp=$Timestamp&Version=2011-08-01";
$String = str_replace("\n", "", $String);
$Prepend = "GET\nwebservices.amazon.com\n/onca/xml\n";
$PrependString = $Prepend . $String;
$Signature = base64_encode(hash_hmac("sha256", $PrependString, $SecretAccessKey, True));
$Signature = str_replace("+", "%2B", $Signature);
$Signature = str_replace("=", "%3D", $Signature);
$BaseUrl = "http://webservices.amazon.com/onca/xml?";
$SignedRequest = $BaseUrl . $String . "&Signature=" . $Signature;
$XML = simplexml_load_file($SignedRequest);
print_r($xml); // output

Amazon API page number not working

I'm trying to fetch a list of results for a search through Amazon API to list products on my website. Everything works except for specifying the page number that I want to retrieve. It always fetches page 1 for some reason.
$SecretAccessKey = "xxx";
$request['AWSAccessKeyId'] = "xxx";
$request['AssociateTag'] = "xxx";
$request['Timestamp'] = gmdate("Y-m-d\TH:i:s\Z");
$request['ResponseGroup'] = "ItemAttributes,Offers,Images";
$request['ItemPage'] = 1;
$request['Service'] = 'AWSECommerceService';
$request['Version'] = '2011-08-01';
$request['Operation'] = 'ItemSearch';
$request['SearchIndex'] = $search['category_name'];
$request['Keywords'] = $search['text'];
$request['Page'] = 5;
ksort($request); // Sorts in order of key
$Prepend = "GET\nwebservices.amazon.com\n/onca/xml\n";
$String = http_build_query($request);
$PrependString = str_replace('+', '%20', $Prepend . $String);
$Signature = base64_encode(hash_hmac("sha256", $PrependString, $SecretAccessKey, True));
$Signature = urlencode($Signature);
$BaseUrl = "http://webservices.amazon.com/onca/xml?";
$SignedRequest = $BaseUrl . $String . "&Signature=" . $Signature;
// Fetch the generated URL
$xml = simplexml_load_file($SignedRequest);
I've tried with $request['Page'], $request['page'], $request['Pages'] and $request['pages']. None seem to work to pull the correct page. Does anyone know what this parameter is supposed to be named?
Turns out it was ItemPage.
$request['ItemPage'] = 5;

Output # and # as normal text on Twitter feed

I'm outputting a Twitter feed using the variable $tweet, when it outputs the tweet it stops when it hits an # or hastag, is it possible to just output those as normal text?
E.g
This is what happens when it tries to show a #
(i.e as soon as it hits the # it stops, the same applies to a hashtag)
UPDATE:
<?php
function parseTweet($text) {
$pattern_url = '~(?>[a-z+]{2,}://|www\.)(?:[a-z0-9]+(?:\.[a-z0-9]+)?#)?(?:(?:[a-z](?:[a-z0-9]|(?<!-)-)*[a-z0-9])(?:\.[a-z](?:[a-z0-9]|(?<!-)-)*[a-z0-9])+|(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))(?:/[^\\/:?*"|\n]*[a-z0-9])*/?(?:\?[a-z0-9_.%]+(?:=[a-z0-9_.%:/+-]*)?(?:&[a-z0-9_.%]+(?:=[a-z0-9_.%:/+-]*)?)*)?(?:#[a-z0-9_%.]+)?~i';
'#([A-Za-z0-9_]+)';
$tweet = preg_replace('/(^|\s)#(\w+)/', '\1#\2', $text);
$tweet = preg_replace('/(^|\s)#(\w+)/', '\1#\2', $tweet);
$tweet = preg_replace("#(^|[\n ])(([\w]+?://[\w\#$%&~.\-;:=,?#\[\]+]*)(/[\w\#$%&~/.\-;:=,?#\[\]+]*)?)#is", "\\1[link]", $tweet);
return $tweet;
}
$username='teamworksdesign'; // set user name
$format='json'; // set format
$tweet=json_decode(file_get_contents("http://api.twitter.com/1/statuses/user_timeline/{$username}.{$format}")); // get tweets and decode them into a variable
$theTweet = parseTweet($tweet[0]->text);
$newTweet = substr($theTweet,0,65);
echo '<a class="tweet" rel="nofollow" href="http://www.twitter.com/teamworksdesign"> "' . $newTweet . '..."</a>';
?>
EDIT: The answer is in the comments.
Some parts of that function appear to be unnecessary. You could have a go with this function instead, as I know this one works?
function parseTweet($ret) {
$ret = preg_replace("#(^|[\n ])([\w]+?://[\w]+[^ \"\n\r\t< ]*)#", "\\1\\2", $ret);
$ret = preg_replace("#(^|[\n ])((www|ftp)\.[^ \"\t\n\r< ]*)#", "\\1\\2", $ret);
$ret = preg_replace("/#(\w+)/", "#\\1", $ret); // Usernames
$ret = preg_replace("/#(\w+)/", "#\\1", $ret); // Hash Tags
return $ret;
}
Now - not knowing exactly where your problem is, this is what i do when i am reading a tweet to display as HTML:
// filter the user's username out of tweets
$tweet = str_replace($username . ": ", "", $tweet);
// turn URLs into hyperlinks
$tweet = preg_replace("/(http:\/\/)(.*?)\/([\w\.\/\&\=\?\-\,\:\;\#\_\~\%\+]*)/", "Link", $tweet);
// link to users in replies
$tweet = preg_replace("(#([a-zA-Z0-9\_]+))", "\\0", $tweet);
// add the time posted
$tweet = $tweet . " <span class=\"tweetwhen\">" . $posted . "</span>";

Categories