2012-09-13 29 views
1

我努力用Transient API創建網頁緩存。當我嘗試保存整個源代碼時,出現了一些問題。我懷疑WordPress在內部更正了格式。在那種情況下,是否有保存數據的好方法?使用WordPress瞬態API保存網頁

下面的代碼已準備好作爲插件運行並演示該問題。如果未創建緩存,則會顯示一個網頁,但一旦創建緩存並嘗試顯示緩存的數據,就會顯示一個空白頁面。

<?php 
/* Plugin Name: Sample Transient */ 

add_action('admin_menu', 'sample_transient_menu'); 
function sample_transient_menu() { 
    add_options_page(
     'Sample Transient', 
     'Sample Transient', 
     'manage_options', 
     'sample_transient', 
     'sample_transient_admin'); 
} 
function sample_transient_admin() { 
    ?> 
    <div class="wrap"> 
    <?php 

     $strTransient = 'sample_transient_html'; 
     $html = get_transient($strTransient);  
     if(false === $html) { 
      echo 'cache is not used: ' . $strTransient . '<br />';  
      $html = wp_remote_get('http://www.google.com'); 
      $html = $html['body']; 
      // $html = '<div>hello world</div>'; // <-- this works fine 
      set_transient($strTransient, htmlspecialchars($html), 60); 

      $tmp = get_transient($strTransient); 
      if (false === $tmp) 
       echo 'transient is not saved.'; 
      else 
       echo 'transient is now saved: ' . $strTransient;  
     } else 
      echo 'cache is used. <br />'; 
     print_r(htmlspecialchars_decode($html)); 
    ?> 
    </div> 
    <?php 
} 

[編輯] 而且,但是應當理解,如果有人能夠提供對於編碼問題的解決方案。目前它只顯示破碎的字符。

回答

0

加密字符串剛剛工作。雖然我不確定速度。

<?php 
/* Plugin Name: Sample Transient */ 

add_action('admin_menu', 'sample_transient_menu'); 
function sample_transient_menu() { 
    add_options_page(
     'Sample Transient', 
     'Sample Transient', 
     'manage_options', 
     'sample_transient', 
     'sample_transient_admin'); 
} 
function sample_transient_admin() { 
    ?> 
    <div class="wrap"> 
    <?php 

     $strTransient = 'sample_transient_html3'; 
     $key = 'sample_transient'; 
     $html = get_transient($strTransient); 
     if(false === $html) { 
      echo 'cache is not used: ' . $strTransient . '<br />';  
      $html = wp_remote_get('http://www.google.com'); 
      $html = $html['body']; 
      $savehtml = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $html, MCRYPT_MODE_CBC, md5(md5($key)))); 
      set_transient($strTransient, $savehtml, 60); 
     } else { 
      echo 'cache is used. <br />'; 
      $html = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($html), MCRYPT_MODE_CBC, md5(md5($key))); 
     } 
     print_r($html); 
    ?> 
    </div> 
    <?php 
} 

參考:Best way to use PHP to encrypt and decrypt passwords?

相關問題