douti9253 2014-01-26 19:23
浏览 50

在mongodb中插入推文失败

 <?php
 require 'app_tokens.php';
 require 'tmhOAuth-master/tmhOAuth.php';
 $query = !empty($_GET['query']) ? htmlspecialchars($_GET['query']) : "shahrukh";

$connection = new tmhOAuth(array(
'consumer_key' => $consumer_key,
'consumer_secret' => $consumer_secret,
'user_token' => $user_token,
'user_secret' => $user_secret
));

// Get the timeline with the Twitter API
$http_code = $connection->request('GET',$connection->url('1.1/search/tweets'),
array('q' => $query, 'count' => 20, 'lang' => 'en'));
// Request was successful
  if ($http_code == 200)
   {
      // Extract the tweets from the API response
      $response = json_decode($connection->response['response'],true);
      $tweet_data = $response['statuses'];

     // Accumulate tweets from results
     $tweet_stream = '[';
        foreach ($tweet_data as $tweet)
           {
               // Add this tweet's text to the results

               $tweet_stream .= ' "<br>"{ "tweet":' . json_encode($tweet['text']) . ' },';
           }
     $tweet_stream = substr($tweet_stream, 0, -1);
     $tweet_stream .= ']';
   // Send the tweets back to the Ajax request
    print $tweet_stream;


// Connect to Mongo and set DB and Collection

$mongo = new Mongo();
$db = $mongo->twitter;
$collection = $db->tweets;

// Convert JSON to a PHP array
$tweet_stream = json_decode($tweet_stream,true);

// Loop array and create seperate documents for each tweet
foreach ($tweet_stream as $item)
 {

 $collection->insert($item);
}


 // fetch all tweets from the collection
 $posts = $collection->find();

 foreach ($posts as $post) {
// display the posts
print $post;
  }
 }
// Handle errors from API request
else
  {
    if ($http_code == 429) 
      {
          print 'Error: Twitter API rate limit reached';
      }
   else 
     {
         print 'Error: Twitter was not able to process that request';
     }
} 

The execution of above code sucessfully retrieves the tweets related to shahrukh.The problem is it do not insert the tweets in mongodb and message given is " ! ) Warning: Invalid argument supplied for foreach() in C:\wamp\www\search.php on line 51".Why is it so??Please go through it and hel me.

  • 写回答

1条回答 默认 最新

  • dpzo13732 2014-01-26 19:32
    关注

    you must change a line

    $tweet_stream .= ' "<br>"{ "tweet":' . json_encode($tweet['text']) . ' },';
    

    to

    $tweet_stream .= '{ "tweet":' . json_encode($tweet['text']) . ' },';
    
    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集