在mongodb中插入推文失败

时间:2014-01-26 19:23:54

标签: php mongodb twitter

 <?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';
     }
} 

执行上面的代码成功地检索了与shahrukh相关的推文。问题是它没有在mongodb中插入推文并且给出的消息是“!”警告:在C:\ wamp \ www中为foreach()提供的参数无效\ search.php在第51行“。为什么会这样?请通过它并帮助我。

1 个答案:

答案 0 :(得分:1)

你必须改变一行

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

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