从其他网站获取html数据并缓存+作为最终用户有可能吗?

从其他网站获取html数据并缓存+作为最终用户有可能吗?

问题描述:

我在WordPress的下面的代码,其抓住用于一菜单的HTML代码上的店铺所以博客和商店(这是一个完全不同的系统)具有相同的动态菜单,然而它需要一段时间来加载,是代码效率低下还是我需要走下缓存路线?从其他网站获取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]; 
       ?> 

我的另一个问题是,最好我想包括登录/从博客上的铺得过我的帐户链接,但是这个是基于会话的店,有没有像这需要上面的任何代码考虑最终用户会话?也许就像装上代表最终用户的外部链接以获得内容(如在商店的用户会话将被激活)

我回答您的第一个问题,这取决于如何往往菜单的改变,你可以考虑使用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]; 
?> 
+0

只是为了检查,这是我该怎么做? ',$ content); \t \t \t \t \t $ second_step = explode(“”,$ first_step [1]); \t \t \t \t \t回波$ second_step [0]; ?> – bigdaveygeorge 2014-10-27 19:35:26

+0

@ 6h8j5我已经更新了我的答案与一些示例代码,应该做你需要什么。 – 2014-10-27 21:16:32