0

我正在使用以下代码:

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 秒的明显延迟。一如既往,非常感谢任何帮助。

4

1 回答 1

1

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

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

于 2012-10-23T08:28:48.227 回答