【问题标题】:Getting html data from another website and caching + is it possible as end user?从另一个网站获取 html 数据并缓存 + 是否可以作为最终用户?
【发布时间】:2014-10-27 17:17:29
【问题描述】:

我在 wordpress 中有以下代码,它获取商店菜单的 HTML 代码,因此博客和商店(这是一个完全不同的系统)具有相同的动态菜单,但是加载需要一段时间,是代码效率低下还是我需要走缓存路线?

                <?php
                $url = 'http://localhost:8080/mystore/';
                $content = file_get_contents($url);
                $first_step = explode( '<nav class="top">' , $content );
                $second_step = explode("</nav>" , $first_step[1] );
                echo $second_step[0];
                ?>

我的另一个问题是,理想情况下,我也想在博客上包含来自商店的登录/我的帐户链接,但是在商店中这是基于会话的,是否有任何类似上述的代码考虑到结尾用户会话?比如可能代表最终用户加载外部链接以获取内容(因为商店上的用户会话将处于活动状态)

【问题讨论】:

    标签: php wordpress session file-get-contents


    【解决方案1】:

    我回答您的第一个问题,根据菜单更改的频率,您可以考虑使用 Transients API 缓存 HTML。您的示例如下所示:

    <?php
        if ( false === ( $content = get_transient( 'shop_menu_html' ) ) ) {
            // Transient is not present or has expired, so set it
            $url = 'www.externalurl.com';
            $content = file_get_contents( $url );
            set_transient( 'shop_menu_html', $content, 12 * HOUR_IN_SECONDS );
        }
        $first_step = explode( '<nav class="top">' , $content );
        $second_step = explode("</nav>" , $first_step[1] );
        echo $second_step[0];
    ?>
    

    【讨论】:

    • 只是检查一下,我会这样做吗? ', $content); $second_step = explode("" , $first_step[1] );回声 $second_step[0]; ?>
    • @6h8j5 我已经用一些示例代码更新了我的答案,这些示例代码应该可以满足您的需要。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-23
    • 2013-08-15
    • 2015-04-26
    • 1970-01-01
    相关资源
    最近更新 更多