I am using the Twitter Search API 1.1 to search for tweets on a particular keyword and display the results as a search results page at motherpipe.co.uk.
I have managed to get the Oauth working with the help of James Mallison at http://github.com/j7mbo/twitter-api-php.
I am stuck at the stage of taking the actual response I get from Twitter and display it normally in divs in HTML (using PHP). This is the reply I get: https://motherpipe.co.uk/staging/index2.php.
I just can't seem to write a simple loop to display only the 'screen_name' and 'text'.
So far I have tried different versions of this:
$url = 'https://api.twitter.com/1.1/search/tweets.json';
$requestMethod = 'GET';
$getfield = '?q=sweden&result_type=recent';
$twitter = new TwitterAPIExchange($settings);
echo $twitter ->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();
$response = json_decode($twitter);
foreach($response as $tweet)
{
echo "{$tweet->screen_name} {$tweet->text}\n";
}
Any feedback or ideas on how to loop through this correctly would be much appreciated.
Cheers
I dont use james code but I get it working other way round
<ul>
<?php $get_tweets = $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=".$twitteruser."&count=".$notweets);
foreach($get_tweets as $tweet) {
$tweet_desc = $tweet->text;
?>
<li><?php echo $tweet_desc ?></li>
<?php }?>
</ul>
You can see a working Twitter Api V1.1 at the footer of this page. If you want something like this or further customisation let me know .
If you would do a var_dump of $response, you would probably get a better idea of the structure. Looks like you need to loop over $response->statuses. The user information is under $tweet->user->screen_name and the tweet text is under $tweet->text. So:
$response = json_decode($twitter);
foreach($response->statuses as $tweet)
{
echo "{$tweet->user->screen_name} {$tweet->text}\n";
}
The user information is under $tweet->user->screen_name and the tweet text is under $tweet->text
$response = json_decode($twitter);
foreach($response->statuses as $tweet)
{
echo "{$tweet->user->screen_name} {$tweet->text}<br />";
}
OR also you can use this too
$response = json_decode($twitter, true);
$counter = 0;
foreach($response['statuses'] as $tweet)
{
echo "{$tweet[$counter]['user']['screen_name'] {$tweet[$counter]['text']}<br />";
$counter +=1;
}
So the answer (thanks to Prisoner, Jonathan Kuhn and Mubin Khalid) is, in order to display the response from the Twitter Search API, assign a variable to the Twitter JSON response. This will enable you to loop through and display whatever you want from the response.
$url = 'https://api.twitter.com/1.1/search/tweets.json';
$requestMethod = 'GET';
$getfield = '?q=sweden&result_type=recent';
$twitter = new TwitterAPIExchange($settings);
$api_response = $twitter ->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();
$response = json_decode($api_response);
foreach($response->statuses as $tweet)
{
echo "{$tweet->user->screen_name} {$tweet->text}\n";
}
Related
I'm trying to return a value from my API using PHP, api can be found here:
code is as follows:
Im not seeing the echo on my page, don't see any errors and I believing im reading the json in correctly. Any help appreciated!
<?php
$titleid = 2;
$url = "http://kmoffett07.lampt.eeecs.qub.ac.uk/serverSide/buildapi.php?id={$titleid}";
$response = file_get_contents($url);
$returnvalue = json_decode($response, true);
echo $returnvalue["Age"];
?>
From what I can tell, the json is not valid on the server side (due to the "connected to db" text in front of the {} part). I think it would be a good idea to fix the server side response json data, if possible!
For now, here is a way to get the value it looks like you are intending to retrieve:
<?php
$titleid = 2;
$url = "http://kmoffett07.lampt.eeecs.qub.ac.uk/serverSide/buildapi.php?id={$titleid}";
$response = file_get_contents($url);
$adjusted_response = str_replace('connected to db', '', $response);
$returnvalue = json_decode($adjusted_response, true);
echo $returnvalue['tv_shows']['Age'];
?>
Output:
$ php example.php
16+
If the server side json data is fixed, I think you could shorten the code to something like this:
<?php
$titleid = 2;
$url = "http://kmoffett07.lampt.eeecs.qub.ac.uk/serverSide/buildapi.php?id={$titleid}";
$response = file_get_contents($url);
$returnvalue = json_decode($response, true);
echo $returnvalue['tv_shows']['Age'];
?>
The thing is that $response is returned as string , in order to fix that you need to edit your backend and make it give the response without "connected to db"
Having read the The Twitter Search API as part of Twitter’s v1.1 REST API and searching here I am still stumped as to how to format the query.
K.Jack was able to get it working with a search for screen names and I thought I could use his code and adapt it but no such luck.
Here is code for what I have working using a static search term in the getfield area and including the form I am trying to incorporate.
I am searching for tweets. In K.Jack's issue he was using the search for screename and had his question answered with this snippet;
$getfield = "?screen_name=".$_GET['screen_name'];
<?php
require_once('TwitterAPIExchange.php');
/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
$settings = array(
'oauth_access_token' => "MY_KEY_HERE",
'oauth_access_token_secret' => "MY_KEY_HERE",
'consumer_key' => "MY_KEY_HERE",
'consumer_secret' => "MY_KEY_HERE",
);
$url = 'https://api.twitter.com/1.1/search/tweets.json';
$getfield = '?q=question&count=1';
$requestMethod = 'GET';
$twitter = new TwitterAPIExchange($settings);
$string = json_decode($twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest(),$assoc = TRUE);
if($string["errors"][0]["message"] != "") {echo "<h3>Sorry, there was a problem.</h3><p>Twitter returned the following error message:</p><p><em>".$string[errors][0]["message"]."</em></p>";exit();}
foreach($string as $items)
{
for($i = 0; $i < count($items); $i++) {
echo "". $items[$i]['text']. "<br />";
}
}
print ($_GET['question']);
?>
<h3>Enter the name here</h3>
<form action="" method="GET">
<input type="text" name="question" /><br />
<input type="submit" />
</form>
This is my first question here. I tend to muddle through learning by experimenting but I have spent too long on this with too little php knowledge and just had to ask.
thank you
How do you decode the tweets.json string returned from a twitter search API request?
I have looked through answers to similar questions. Those answers do show how to make a call, and how to display the data returned, but those don't deal with the issue of dealing with the structure of the data that is returned from the tweets.json API call.
Here's the code - it uses the twitter API. It requests search results.
<?php
require_once('../TwitterAPIExchange.php');
$settings = array(
'oauth_access_token' => "......",
'oauth_access_token_secret' => "......",
'consumer_key' => "......",
'consumer_secret' => "......"
);
$requestMethod = 'GET';
//$url = "https://api.twitter.com/1.1/statuses/user_timeline.json"; // I can decode output from this
//$getfield = "?screen_name=J7mbo&count=5"; // I can decode output from this
$url = "https://api.twitter.com/1.1/search/tweets.json"; // I can NOT decode output from this
$getfield = "?q=%23J7mbo&result_type=recent"; // I can NOT decode output from this
$twitter = new TwitterAPIExchange($settings);
$string = $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest(); // from stackOverflow
$string = json_decode($string, $assoc = TRUE); // seems i cannot use json_decode for output from tweets.json
if ($string["errors"][0]["message"] != "")
{
echo "twitter error message:" . $string[errors][0]["message"];
exit();
}
foreach ($string as $items)
{
echo "tweet text =[". $items['text']."]<br />";
}
?>
If I was using a twitter API timeline call, I could use json_decode and access $items['text'] for each of the returned tweets
But I want to use the twitter API search call (tweets.json). json_decode does not properly decode the data from this search call, it only returns two empty $items['text']
So what's the best way to decode the tweets.json string returned from a twitter API request?
You need to iterate through the $items array and get the text property off of there.
foreach ($items as $item) {
echo "tweet text =[". $item['text']."]<br />";
}
After examining the data I noticed that is consisted of two JSON encoded strings, named statuses and search_metadata. I extracted the statuses string and was able to decode it using json_decode.
using below code, TWITTER API and PHP, i have successfully fetch/get my twitter timeline.
$url = 'https://api.twitter.com/1.1/statuses/home_timeline.json';
$getfield = '?screen_name=twitter';
$requestMethod = 'GET';
$twitter = new TwitterAPIExchange($settings);
echo $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();
my concern is, the data/results displayed fills up my whole window screen with text. im not sure how to apply CSS or HTML on it.
[{"created_at":"Sun Dec 09 05:21:29 +0000 2012","id":2232376342522313442,"id_str":"277231523253442","text":"http:\/\/t.co\/ro74jh4","source":"web","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"
the tutorial im following didn't mentioned how to arrange the fetched data.
You'll need to parse the JSON data that you got from object from Twitter. Here is an example. You can use the array syntax to find which values you want to look up.
$response = $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();
$obj = json_decode($response, true);
echo "<div><ul>";
foreach ($obj["statuses"] as $index => $result) {
$tweet = $result['text'];
$user = $result['user']['screen_name'];
$profile_image = $result['user']['profile_image_url'];
echo "<li>";
echo "<img src=\"".$profile_image."\" width=\"25px\" height=\"25px\" />";
echo "#$user";
echo " $tweet";
echo "</li>";
}
echo "</ul></div>";
I am using twitter API v1.1 to get tweets in my web application the code for getting tweets is as
$name = 'zkalvi';
$url = "https://api.twitter.com/1.1/search/tweets.json/".$name;
$tweets = json_decode(file_get_contents($url));
echo '<ul>';
foreach($tweets as $tweet) {
echo '<li>'.$tweet->text.'</li>';
}
echo '</ul>';
and $name = 'zkalvi';
$url = "https://api.twitter.com/1.1/search/tweets.json/".$name;
$tweets = simplexml_load_file($url);
echo '<ul>';
foreach($tweets as $tweet) {
echo '<li>'.$tweet->text.'</li>';
}
echo '</ul>';
both of these codes are not showing the tweets.
Please help me why the tweets are not showing and how could I show the tweets?
Thanks in advance.
first of all, the way you are calling is wrong, your url should be like this
https://api.twitter.com/1.1/search/tweets.json?q=zkalvi.
By this url you will get following output
{"errors":[{"message":"Bad Authentication data","code":215}]}
This is because , in twitter 1.1 version, most of thing needs authentication. So better you use twitter server side library for getting results.
Here is link for twitteroauth library for php
twitteroauth