Cakephp Twitch.Tv API加载时间

时间:2012-10-23 06:39:01

标签: php json cakephp

我正在使用以下代码:

public function getUser($name) {
        $return = array();
        $file = array();
        $httpSocket = new HttpSocket();
        $url = $this->baseUrl . $name . $this->apiKey;
        $temp = $httpSocket->get($url);
        $file = $temp->body;
        $file = explode(',', $file);
        $i = 0;

        foreach ($file as $info) {
            $info = str_replace("{", "", $info);
            $info = str_replace("}", "", $info);
            $info = str_replace('"', "", $info);
            $info = str_replace("[", "", $info);
            $info = str_replace("]", "", $info);
            $temp = explode(':', $info, 2);

            if ($temp[0] == 'stream') {
                $temp[1] = str_replace("game:", "", $temp[1]);
                if ($temp[1] == 'StarCraft II: Wings of Liberty') {
                    $temp[1] = 'starcraft-II';
                }
                $return[$i]['game'] = $temp[1];
            } elseif ($temp[0] == 'teams') {
                $temp[1] = str_replace("name:", "", $temp[1]);
                if ($temp[1] != '') {
                    $return[$i]['teams'] = $temp[1];
                } else {
                    $return[$i]['teams'] = null;
                }
            } else {
                if (isset($temp[1])) {
                    $return[$i][$temp[0]] = $temp[1];
                }
            }
        }

        return $return;
    }

我想知道是否有什么办法可以减少这个脚本的加载时间。我正在从TwitchTV中提取一个json文件作为记录。该功能仅适用于页面刷新/加载,页面渲染中有明显的2-3秒延迟。一如既往,我们非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

你知道API的响应是json吗?为什么要手动解析响应而不是使用json_decode()?使用json_decode()并查看它将生成什么。您可以删除90%的代码。

此外,我会根据您的需要缓存API响应,持续几分钟到几个小时。阅读本书http://book.cakephp.org/2.0/en/core-libraries/caching.html的缓存章节。页面应立即加载刷新,因为它不需要再进行其他API调用。

相关问题