2015-04-19 69 views
-1

我有一個應用程序將json數據從Twitter API發送到PHP腳本,所以我嘗試將我的json數據轉換爲數組並將其插入到mongodb中但是,以下警告:插入來自twitter api的json數據,然後使用php插入到mongodb

Invalid argument supplied for foreach() 

這是我的代碼部分:

<?php 
session_start(); 
$conn = new MongoClient("mongodb://$dbhost"); 
$db = $conn->$dbname; 
// // access collection 
$collection = $db->tweets; 
$tweet = $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=".$twitteruser."&count=".$notweets); 
$curl = curl_init(); 
curl_setopt($curl,CURLOPT_URL,1); 
curl_setopt($curl, CURLOPT_HEADER, 0); 
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($tweet)); 
$usertimeline = curl_exec($curl); 
curl_close($curl); 

$usertimeline = json_decode($usertimeline); 
// Loop array and create seperate documents for each tweet 
foreach ($usertimeline as $id => $item) { 
$collection->insert($item); 
} 
+0

請考慮重命名這個問題的標題,因爲它與mongo毫無關係,與twitter沒什麼關係。 – disrvptor

回答

0

這是爲我工作的。
這是代碼的一部分,只是您必須確定您在PHP中擁有curl支持。

<?php 
session_start(); 
require_once("twitteroauth-master/twitteroauth/twitteroauth.php"); 
$connection = getConnectionWithAccessToken($consumerkey, $consumersecret,$accesstoken, $accesstokensecret); 
$tweets = $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=".$twitteruser."&count=".$notweets); 
$tweets = json_encode($tweets); 
$connection = new MongoClient(); 
$tweetCollection = $connection->test->tweets; 
$tweetCollection->insert(json_decode($tweet)); 
?> 
0

根據捲曲PHP文件,curl_exec返回真/假,除非CURLOPT_RETURNTRANSFER選項設置爲true。嘗試將該參數設置爲true。

0

添加選項CURLOPT_RETURNTRANSFER

curl_setopt($curl,CURLOPT_RETURNTRANSFER,TRUE); 

我也建議檢查捲曲和JSON解析錯誤。

<?php 
session_start(); 
$conn = new MongoClient("mongodb://$dbhost"); 
$db = $conn->$dbname; 
// access collection 
$collection = $db->tweets; 
$tweet = $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=".$twitteruser."&count=".$notweets); 
$curl = curl_init(); 

curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); 
curl_setopt($curl, CURLOPT_URL, 1); 
curl_setopt($curl, CURLOPT_HEADER, 0); 
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($tweet)); 
$usertimeline = curl_exec($curl); 

if (curl_errno($curl) != 0) { 
    // an error appeared 
} 

curl_close($curl); 

if (($usertimeline = json_decode($usertimeline) === NULL) { 
    // JSON parse error 
    // empty $usertimeline or invalid JSON 
    // (happens when transfer was not completely finished). 
} 

// Loop array and create seperate documents for each tweet 
foreach ($usertimeline as $id => $item) { 
    $collection->insert($item); 
}