Silverstripe: Convert twitter JSON string to Dataobject to loop though in template

六月ゝ 毕业季﹏ 提交于 2019-12-11 06:25:47

问题


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?


回答1:


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




回答2:


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);

    }


来源:https://stackoverflow.com/questions/19888110/silverstripe-convert-twitter-json-string-to-dataobject-to-loop-though-in-templa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!