为foreach()提供的参数无效 - PHP

时间:2015-12-04 02:21:53

标签: php api twitter

我试图使用twitter API来显示推文。我正在使用TwitterAPIExchange。

我收到关于我的每个循环的错误但我不知道为什么。它说为foreach()提供了一个无效的参数。这是为什么?

我已经为这个问题编辑了我的代币和密钥。

<?php
require_once('TwitterAPIExchange.php');

$settings = array(
'oauth_access_token' => "",
'oauth_access_token_secret' => "",
'consumer_key' => "",
'consumer_secret' => ""
);


$url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
$requestMethod = "GET";

if (isset($_GET['user'])) {$user = $_GET['user'];} else {$user = "bbcnews";}
if (isset($_GET['count'])) {$count = $_GET['count'];} else {$count = 20;}

$getfield = "?screen_name=$user&count=$count";

$twitter = new TwitterAPIExchange($settings);

$string = json_decode($twitter->setGetfield($getfield)
                            ->buildOauth($url, $requestMethod)
                            ->performRequest(),$assoc = TRUE);
if($string["errors"][0]["message"] != "") {
    echo "<h3>Sorry, there was a problem.</h3><p>Twitter returned the       following error message:</p><p><em>".$string[errors][0]["message"]."</em></p>";
exit();
}

foreach($string as $items){
    echo "Time and Date of Tweet: ".$items['created_at']."<br />";
    echo "Tweet: ". $items['text']."<br />";
    echo "Tweeted by: ". $items['user']['name']."<br />";
    echo "Screen name: ". $items['user']['screen_name']."<br />";
    echo "Followers: ". $items['user']['followers_count']."<br />";
    echo "Friends: ". $items['user']['friends_count']."<br />";
    echo "Listed: ". $items['user']['listed_count']."<br /><hr />";
}
?>

如果有人能够解释出现了什么问题并尽可能提供解决方案,那就太棒了,谢谢!

编辑:我试图在本地主机上运行它。

Twitter API交换代码:

<?php

class TwitterAPIExchange
{
private $oauth_access_token;
private $oauth_access_token_secret;
private $consumer_key;
private $consumer_secret;
private $postfields;
private $getfield;
protected $oauth;
public $url;

public function __construct(array $settings)
{
    if (!in_array('curl', get_loaded_extensions())) 
    {
        throw new Exception('You need to install cURL, see: http://curl.haxx.se/docs/install.html');
    }

    if (!isset($settings['oauth_access_token'])
        || !isset($settings['oauth_access_token_secret'])
        || !isset($settings['consumer_key'])
        || !isset($settings['consumer_secret']))
    {
        throw new Exception('Make sure you are passing in the correct parameters');
    }
    $this->oauth_access_token = $settings['oauth_access_token'];
    $this->oauth_access_token_secret = $settings['oauth_access_token_secret'];
    $this->consumer_key = $settings['consumer_key'];
    $this->consumer_secret = $settings['consumer_secret'];
}


public function setPostfields(array $array)
{
    if (!is_null($this->getGetfield())) 
    { 
        throw new Exception('You can only choose get OR post fields.'); 
    }

    if (isset($array['status']) && substr($array['status'], 0, 1) === '@')
    {
        $array['status'] = sprintf("\0%s", $array['status']);
    }

    $this->postfields = $array;

    return $this;
}


public function setGetfield($string)
{
    if (!is_null($this->getPostfields())) 
    { 
        throw new Exception('You can only choose get OR post fields.'); 
    }

    $search = array('#', ',', '+', ':');
    $replace = array('%23', '%2C', '%2B', '%3A');
    $string = str_replace($search, $replace, $string);  

    $this->getfield = $string;

    return $this;
}


public function getGetfield()
{
    return $this->getfield;
}


public function getPostfields()
{
    return $this->postfields;
}


public function buildOauth($url, $requestMethod)
{
    if (!in_array(strtolower($requestMethod), array('post', 'get')))
    {
        throw new Exception('Request method must be either POST or GET');
    }

    $consumer_key = $this->consumer_key;
    $consumer_secret = $this->consumer_secret;
    $oauth_access_token = $this->oauth_access_token;
    $oauth_access_token_secret = $this->oauth_access_token_secret;

    $oauth = array( 
        'oauth_consumer_key' => $consumer_key,
        'oauth_nonce' => time(),
        'oauth_signature_method' => 'HMAC-SHA1',
        'oauth_token' => $oauth_access_token,
        'oauth_timestamp' => time(),
        'oauth_version' => '1.0'
    );

    $getfield = $this->getGetfield();

    if (!is_null($getfield))
    {
        $getfields = str_replace('?', '', explode('&', $getfield));
        foreach ($getfields as $g)
        {
            $split = explode('=', $g);
            $oauth[$split[0]] = $split[1];
        }
    }

    $base_info = $this->buildBaseString($url, $requestMethod, $oauth);
    $composite_key = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
    $oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
    $oauth['oauth_signature'] = $oauth_signature;

    $this->url = $url;
    $this->oauth = $oauth;

    return $this;
}


public function performRequest($return = true)
{
    if (!is_bool($return)) 
    { 
        throw new Exception('performRequest parameter must be true or false'); 
    }

    $header = array($this->buildAuthorizationHeader($this->oauth), 'Expect:');

    $getfield = $this->getGetfield();
    $postfields = $this->getPostfields();
    $options = array( 
        CURLOPT_HTTPHEADER => $header,
        CURLOPT_HEADER => false,
        CURLOPT_URL => $this->url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 10,
    );
    if (!is_null($postfields))
    {
        $options[CURLOPT_POSTFIELDS] = $postfields;
    }
    else
    {
        if ($getfield !== '')
        {
            $options[CURLOPT_URL] .= $getfield;
        }
    }
    $feed = curl_init();
    curl_setopt_array($feed, $options);
    $json = curl_exec($feed);
    curl_close($feed);
    if ($return) { return $json; }
}


private function buildBaseString($baseURI, $method, $params) 
{
    $return = array();
    ksort($params);

    foreach($params as $key=>$value)
    {
        $return[] = "$key=" . $value;
    }

    return $method . "&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $return)); 
}


private function buildAuthorizationHeader($oauth) 
{
    $return = 'Authorization: OAuth ';
    $values = array();

    foreach($oauth as $key => $value)
    {
        $values[] = "$key=\"" . rawurlencode($value) . "\"";
    }

    $return .= implode(', ', $values);
    return $return;
}
}

1 个答案:

答案 0 :(得分:0)

看起来你试图循环,$ string变量,没有显式声明为数组。

您能提供TwitterAPIExchange.php代码吗?