我正在尝试使用php和JSON数据从twitter获取文本。我用过这个脚本
<?php
session_start();
require_once("twitter/twitteroauth.php"); //Path to twitteroauth library you downloaded in step 3
$twitteruser = "user"; //user name you want to reference
$notweets = 5; //how many tweets you want to retrieve
$consumerkey = "XXXXXXXXX"; //Noted keys from step 2
$consumersecret = "XXXXXXXXX"; //Noted keys from step 2
$accesstoken = "XXXXXXXX"; //Noted keys from step 2
$accesstokensecret = "XXXXXXXXXXXX"; //Noted keys from step 2
function getConnectionWithAccessToken($cons_key, $cons_secret, $oauth_token, $oauth_token_secret) {
$connection = new TwitterOAuth($cons_key, $cons_secret, $oauth_token, $oauth_token_secret);
return $connection;
}
$connection = getConnectionWithAccessToken($consumerkey, $consumersecret, $accesstoken, $accesstokensecret);
$tweets = $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=".$twitteruser."&count=".$notweets);
$json = json_encode($tweets, true);
echo $json;
?>
当我这样做时,它会回复所有json数据,如[{"created_at":"Wed Apr 01 21:34:33 +0000 2015","id":5.8338196298063e+17,"id_str":"583381962980626432","text":"THIS IS A TWEET",ECT
我希望它回显的是"text"
对象中的文本(这是一个TWEET)。我试过添加:
foreach($json as $i){
echo $i['text'];
}
但是得到一个错误。有什么想法吗?
这是完整的JSON
答案 0 :(得分:0)
看起来你试图在编码之后回显数据。而不是$ json,使用$ tweets。
foreach($tweets as $i) {
echo $i['text']
}
如果您希望将推文作为json编码数组进行回显,则将其存储到新数组中并对其进行编码:
$data = array();
foreach($tweets as $i)
array_push($data, $i['text']);
$json = json_encode($data);
答案 1 :(得分:0)
在for()
循环内部,您可以使用$tweets[$i]->text
试试这个:
<?php
for($i = 0; $i < count($tweets); $i++) {
echo $tweets[$i]->text . "<br>";
}
?>
输出:
THIS IS A TWEET
ANOTHER TWEET