使用WordPress Transient API保存网页


Save Web Page with WordPress Transient API

我很难用Transient API创建网页缓存。当我试图保存整个源代码时,出现了问题。我怀疑WordPress内部更正了格式。在这种情况下,有没有一种好的方法可以完整地保存数据?

下面的代码已经准备好作为插件运行,并演示了这个问题。当缓存未创建时,它会显示一个网页,但一旦创建并尝试显示缓存的数据,就会显示一个空白页面。

<?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
}

[编辑]此外,如果有人能为编码问题提供解决方案,我们将不胜感激。目前,它只显示破碎的字符。

刚刚对字符串进行了加密。不过我不确定速度。

<?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
}

参考:使用PHP加密和解密密码的最佳方法?