在twitter搜索中使用geocode API

时间:2017-02-24 07:58:58

标签: php api twitter geocode

我的代码完美无缺。它有一个表单,用户必须输入一个关键字,它将为他们提供该关键字的Twitter搜索结果。 如何使用地理编码在结果中添加用户的IP地址或位置?

这是我的代码:

<?php
include "twitteroauth.php";?>
<?php
$consumer = "...";
$consumersecret = "...";
$accesstoken = "...";
$accesstokensecret = "...";

$twitter = new TwitterOAuth($consumer, $consumersecret, $accesstoken, $accesstokensecret);



?>
<html> 

<head>
<meta charset="UTF-8" />
<title>twitter search</title>
</head> 

<body>
<form action="" method="post">
    <label> Search: <input type="text" name ="keyword"/></label>
</form>

<?php 
  if (isset($_POST['keyword'])){
      $tweets = $twitter->get('https://api.twitter.com/1.1/search/tweets.json?q='.$_POST['keyword'].'&result_type=recent&count=50');
      foreach($tweets as $tweet){
           foreach($tweet as $t){
              echo '<p> <img src="'.$t->user->profile_image_url.'"/><p>Tweet:&nbsp'.$t->text.'<br>';
          }
      }
  }


?>
</body>

</html>

1 个答案:

答案 0 :(得分:1)

以下是对我有用的东西(这里的假设是你所包含的文件是相同的)

require_once 'lib/twitteroauth.php';

define('CONSUMER_KEY', 'your_consumer_key');
define('CONSUMER_SECRET', 'your_consumer_secret');
define('ACCESS_TOKEN', 'your_access_token');
define('ACCESS_TOKEN_SECRET', 'your_access_token_secret');

function search(array $query)
{
  $toa = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
  return $toa->get('search/tweets', $query);
}

$query = array(
  "q" => "hipster",
  "count" => 20,
  "geocode" => "37.781157,-122.398720,1mi" // San Fran, Cali, USA
);
$results = search($query);

foreach ($results->statuses as $result) {
  echo $result->user->screen_name . ": " . $result->text . "\n";
}