这是我的代码:
$latesttweets = $twitterconn>get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=".$twitter_id."&count=".$limit);
foreach ( $latesttweets as $tweet ){
...
$text_url = $tweet->entities->urls[0]->url; // this line gives an error
// test
echo $text_url; // this line doesn't give an error
... code for display tweet ...
}
我试图从对象中检索网址:
"urls": [{
"url": "https:\/\/t.co\/XdXRudPXH5",
"expanded_url": "https:\/\/blog.twitter.com\/2013\/rich-photo-experience-now-in-embedded-tweets-3",
"display_url": "blog.twitter.com\/2013\/rich-phot\u2026",
"indices": [80, 103]
}],
如图所示here。
有趣的是,我已尝试回复并且可行,但下一行后面的错误Notice: Undefined offset: 0
和Notice: Trying to get property of non-object
会一直显示。
(注意:同样适用于urls
数组中的所有其他数组。我确定它与..->urls[0]->..
有关,但我看到了别无他法。)
我做错了吗?
答案 0 :(得分:1)
好的问题是urls[0]->
不是PHP中的有效对象,您应该使用
$text_url = $tweet->entities->urls{'0'}->url;
代替。
但是在PHP 5+中,urls[0]->
应该可以正常工作
以下是示例。
$str = '{
"text": "Four more years. http://t.co/bAJE6Vom",
"entities": {
"hashtags": [],
"symbols": [],
"urls": [
{
"url": "https://t.co/XdXRudPXH5",
"expanded_url": "https://blog.twitter.com/2013/rich-photo-experience-now-in-embedded-tweets-3",
"display_url": "blog.twitter.com/2013/rich-phot…",
"indices": [
80,
103
]
}
],
"user_mentions": [],
"media": [
{
"id": 266031293949698050,
"id_str": "266031293949698048",
"indices": [
17,
37
],
"media_url": "http://pbs.twimg.com/media/A7EiDWcCYAAZT1D.jpg",
"media_url_https": "https://pbs.twimg.com/media/A7EiDWcCYAAZT1D.jpg",
"url": "http://t.co/bAJE6Vom",
"display_url": "pic.twitter.com/bAJE6Vom",
"expanded_url": "http://twitter.com/BarackObama/status/266031293945503744/photo/1",
"type": "photo",
"sizes": {
"medium": {
"w": 600,
"h": 399,
"resize": "fit"
},
"thumb": {
"w": 150,
"h": 150,
"resize": "crop"
},
"small": {
"w": 340,
"h": 226,
"resize": "fit"
},
"large": {
"w": 800,
"h": 532,
"resize": "fit"
}
}
}
]
}
}
';
$tweet = json_decode($str);
$text_url = $tweet->entities->urls{0}->url;
echo $text_url ;