1

I'm using the twitter API to get a timeline which I want to output through my template. I'm getting the feed like so:

public static function getTwitterFeed(){
    $settings = array(
        'oauth_access_token' => "xxx",
        'oauth_access_token_secret' => "xxx",
        'consumer_key' => "xxx",
        'consumer_secret' => "xxx"
    );

    $url = 'https://api.twitter.com/1.1/statuses/user_timeline.json';
    $getfield = '?screen_name=xxx&count=5';
    $requestMethod = 'GET';
    $twitter = new TwitterAPIExchange($settings);
    $returnTwitter = $twitter->setGetfield($getfield)
                 ->buildOauth($url, $requestMethod)
                 ->performRequest();
    return json_decode($returnTwitter);

}

This returns an array of objects (the tweet is the object) and I want to be able to loop through it in my template like so:

<% loop TwitterFeed %>
    <h4>$created_at</h4>
    <p>$text</p>
<% end_loop %>

As I have it above, the loop is entered once but no values are recognised. How can I achieve this?

igleyy
  • 605
  • 4
  • 16
Fraser
  • 14,036
  • 22
  • 73
  • 118

2 Answers2

4

DataObjects in SilverStripe represent a record from the database, in your case you wound use a ArrayData.
Use $array = Convert::json2array($returnTwitter) or $array = json_decode($returnTwitter, true) instead.
and see https://stackoverflow.com/a/17922260/1119263 for how to use ArrayData

Community
  • 1
  • 1
Zauberfisch
  • 3,870
  • 18
  • 25
1

Thanks to Zauberfisch for pointing me in the right direction. I solved it like so:

public static function getTwitterFeed(){
    $settings = array(
        'oauth_access_token' => "xxx",
        'oauth_access_token_secret' => "xxx",
        'consumer_key' => "xxx",
        'consumer_secret' => "xxx"
    );

    $url = 'https://api.twitter.com/1.1/statuses/user_timeline.json';
    $getfield = '?screen_name=xxx&count=5';
    $requestMethod = 'GET';
    $twitter = new TwitterAPIExchange($settings);
    $returnTwitter = $twitter->setGetfield($getfield)
                 ->buildOauth($url, $requestMethod)
                 ->performRequest();

    $returnTwitter = Convert::json2array($returnTwitter);

            $tweets = array();
            foreach ($returnTwitter as $key => $value) {
                $tweets[] = new ArrayData(array('created_at' => $value['created_at'], 'text' => $value['text']));


            }
                return new ArrayList($tweets);

    }
Fraser
  • 14,036
  • 22
  • 73
  • 118