【发布时间】:2015-06-22 05:18:59
【问题描述】:
我正在尝试使用 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" 对象中的文本(这是一条推文)。我已经尝试添加:
foreach($json as $i){
echo $i['text'];
}
但是得到一个错误。有什么想法吗?
这是完整的 JSON
【问题讨论】:
-
你得到什么错误?你能完整显示你的 json 输出吗?
-
你json_encode之前的$tweets是什么?看起来您只需要将您的结果
json_decode放入一个普通数组中 -
错误是`为 foreach() 提供的参数无效`。如果我不对其进行编码并回显它,它只会输出
array -
在这里尝试
var_dumpforeach($json as $i){ var_dump($i); }结果如何? -
@EkoJunaidiSalam 同样的事情,为 foreach() 提供的参数无效
标签: php arrays json twitter multidimensional-array