0

我有这段代码可以根据计数值(当前设置为 5)创建推文数组,但是,当我尝试显示推文时,除了单词 Array 重复 5 次(而不是实际的推文)之外,我什么也没有得到,任何人都可以帮我解决我做错了什么?

顺便说一句,如果我将计数更改为 1 并回显变量 $tweet,我会正确显示最新的推文。

function get_tweet() {

require 'parts/tmhOAuth.php';
require 'parts/tmhUtilities.php';

$tmhOAuth = new tmhOAuth(array(
 'consumer_key' => 'taken out for security purposes',
 'consumer_secret' => 'taken out for security purposes',
 'user_token' => 'taken out for security purposes',
 'user_secret' => 'taken out for security purposes',
 'curl_ssl_verifypeer' => false
));

$code = $tmhOAuth->request('GET', $tmhOAuth->url('1.1/statuses/user_timeline'), array(
'screen_name' => 'designernewsbot',
'count' => '5'));

$response = $tmhOAuth->response['response'];
$tweets = json_decode($response, true);

// This is to create links in my webpage if links are specified in the tweet
$tweet = $tweets[0]['text'];
$tweet = preg_replace("/([\w]+\:\/\/[\w-?&;#~=\.\/\@]+[\w\/])/", "<a target=\"_blank\" href=\"$1\">$1</a>", $tweet);
$tweet = preg_replace("/#([A-Za-z0-9\/\.]*)/", "<a target=\"_new\" href=\"http://twitter.com/search?q=$1\">#$1</a>", $tweet);
$tweet = preg_replace("/@([A-Za-z0-9\/\.]*)/", "<a href=\"http://www.twitter.com/$1\">@$1</a>", $tweet);

foreach($tweets as $tweet):

    echo $tweet;

endforeach;


}
4

1 回答 1

1

问题出在你的foreach循环中。您正在尝试$echo在循环内打印,这是一个数组。所以你会收到一个Array to string conversion错误。

for这种情况下,循环似乎更合适:

for ($i=0; $i < count($tweets); $i++) { 
    echo $tweets[$i]['text']."\n";
}

更新:

要在推文中显示链接,您可以执行以下操作:

for ($i=0; $i < count($tweets); $i++) { 
    //echo $tweets[$i]['text']."\n";
    $var = preg_replace("/([\w]+\:\/\/[\w-?&;#~=\.\/\@]+[\w\/])/", "<a target=\"_blank\" href=\"$1\">$1</a>", $tweets[$i]['text']);
    $var = preg_replace("/#([A-Za-z0-9\/\.]*)/", "<a target=\"_new\" href=\"http://twitter.com/search?q=$1\">#$1</a>", $var);
    $var = preg_replace("/@([A-Za-z0-9\/\.]*)/", "<a href=\"http://www.twitter.com/$1\">@$1</a>", $var);
    echo $var."\n";
}

我已经对此进行了测试,并且可以正常工作。希望这可以帮助!

于 2013-08-28T19:15:29.057 回答