【问题标题】:How to Cache JSON Objects Into Single File for Faster Page Load Times如何将 JSON 对象缓存到单个文件中以加快页面加载时间
【发布时间】:2013-06-12 18:02:55
【问题描述】:

我一直在寻找一种解决方案,将多个 JSON 对象缓存到我服务器上的单个文件中(没有数据库)。原因是我正在开发一个网站,该网站有来自用户 YouTube 频道的多个 JSON 请求,因此页面需要一段时间才能加载。

我的 PHP 文件的一小部分,它从 YouTube 发出 JSON 请求(这个 json-yt.php 文件中有更多 JSON 请求:

// VNM Jar
$realUserName = 'TheEnijar';
$data = file_get_contents('http://gdata.youtube.com/feeds/api/users/' . $realUserName . '?v=2&alt=json');
$data = json_decode($data, true);
$TheEnijar = $data['entry']['yt$statistics'];

// VNM Jinxed
$realUserName = 'OhhJinxed';
$data = file_get_contents('http://gdata.youtube.com/feeds/api/users/' . $realUserName . '?v=2&alt=json');
$data = json_decode($data, true);
$OhhJinxed = $data['entry']['yt$statistics'];

// VNM Pin
$realUserName = 'ImGreenii';
$data = file_get_contents('http://gdata.youtube.com/feeds/api/users/' . $realUserName . '?v=2&alt=json');
$data = json_decode($data, true);
$ImGreenii = $data['entry']['yt$statistics'];

// VNM Zq
$realUserName = 'Zqonalized';
$data = file_get_contents('http://gdata.youtube.com/feeds/api/users/' . $realUserName . '?v=2&alt=json');
$data = json_decode($data, true);
$Zqonalized = $data['entry']['yt$statistics'];

这是否可能,如果是这样,任何人都可以指出我正确的方向或为我提供解决方案,以便在用户加载页面和 JSON 向所有不同的 YouTube 频道发出请求之前存储 JSON 请求。

【问题讨论】:

    标签: php json api caching youtube


    【解决方案1】:

    说实话,有很多不同的方法可以做到这一点。最简单的方法是为您的数据创建一个 assoc 数组,将其序列化并写入文件。

    $dataArray = array();
    
    // ...
    $data = file_get_contents('http://gdata.youtube.com/feeds/api/users/' . $realUserName . '?v=2&alt=json');
    $dataArray['jinxed'] = $data;
    
    $data = serialize($data);
    file_put_contents('cache.txt', $data);
    

    不如把它拉回来:

    $data = unserialize(file_get_contents('cache.txt'));
    

    但是,正如我所说,还有很多其他方法可以缓存请求。选择其中之一取决于您的缓存系统还需要什么。

    UPD:不要忘记缓存的信息有时会过时,因此您必须每隔一段时间更新缓存。要不保存任何其他值(如缓存时间),请为缓存文件使用 filemtime() 函数。

    【讨论】:

    • 谢谢你的回答,我看错了方向。
    【解决方案2】:

    你可以这样做:

    <?php
    
    function getCachableContent($url){
        $hash = md5($url);
        $cacheFile = "/tmp/foo-cache/$hash";
        if ( file_exists($cacheFile) and filemtime($cacheFile) < time() - 300 ) {
            $data = file_get_contents($cacheFile);
        } else {
            $data = file_get_contents($url);
            file_put_contents($cacheFile, $data);
        }
        return json_decode($data);
    }
    
    $data = getCachableContent('http://gdata.youtube.com/feeds/api/users/' . $realUserName . '?v=2&alt=json');
    

    但我认为最好使用像 redis 这样提供过期时间的解决方案。您还可以为临时目录创建一个 ramdisk(如果您使用的是 linux),这会使其更快。

    【讨论】:

      猜你喜欢
      • 2018-04-05
      • 1970-01-01
      • 1970-01-01
      • 2021-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-15
      相关资源
      最近更新 更多