缓存PHP简单的HTML DOM解析器 [英] Caching PHP Simple HTML DOM Parser

查看:128
本文介绍了缓存PHP简单的HTML DOM解析器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 PHP HTML DOM解析器从外部网站拉取数据。为了减少加载和加快页面渲染时间,我想缓存数据我拉一段时间。我如何做到这一点?

I am using the PHP HTML DOM Parser to pull data from an external website. To reduce load and speed up page rendering time I want to cache data I pull for a certain period. How can I do this?

推荐答案

我写了这个文件缓存功能,它基本上只是替换file_get_contents。您可以指定缓存在 $ offset 中持续的时间,或者使用 $ override 完全覆盖缓存。如果您不想使用/ tmp /,只需将该目录更改为可以读取/写入的内容。

I wrote this file cache function which basically just replaces file_get_contents. You can specify the amount of time the cache should last for in $offset or completely override the cache with $override. If you don't want to use /tmp/, just change that directory to something you can read/write to.

function cache_get_contents($url, $offset = 600, $override = false) {
    $file = '/tmp/file_cache_' . md5($url);
    if (!$override && file_exists($file) && filemtime($file) > time() - $offset)
        return file_get_contents($file);

    $contents = file_get_contents($url);
    if ($contents === false)
        return false;

    file_put_contents($file, $contents);
    return $contents;
}

这篇关于缓存PHP简单的HTML DOM解析器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆