【问题标题】:Using cURL and HTTP headers to cache an XML feed correctly with PHP使用 cURL 和 HTTP 标头通过 PHP 正确缓存 XML 提要
【发布时间】:2011-11-23 15:59:49
【问题描述】:

我正在使用 cURL 获取 XML 提要并将其保存到 XML 文件中,就像这样

if (file_exists($filename) && (filemtime($filename) > time() - 30)) {
    // load cached XML from file
    $output = simplexml_load_file($filename);

    return $output;
} else {
    // Initiate the curl session
    $ch = curl_init();

    // Set the URL
    curl_setopt($ch, CURLOPT_URL, $url);

    // Removes the headers from the output
    curl_setopt($ch, CURLOPT_HEADER, 0);

    // Callback to get custom headers
    curl_setopt($ch, CURLOPT_HEADERFUNCTION, array(&$this,'readHeader'));

    // Return the output instead of displaying it directly
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    // Execute the curl session
    $output = curl_exec($ch);

    // Return headers
    $headers = curl_getinfo($ch);

    // Merge headers into one array
    $this->response_meta_info = array_merge($headers, $this->response_meta_info);

    // Close the curl session
    curl_close($ch);

    // Cache feed
    file_put_contents($filename, $output);

    // XML to object
    $output = simplexml_load_string($output);

    // Return the output as an array
    return  $output;
}

它返回以下 http 标头

Array(
    [url] => http://example.com
    [content_type] => text/xml
    [http_code] => 200
    [header_size] => 425
    [request_size] => 108
    [filetime] => -1
    [ssl_verify_result] => 0
    [redirect_count] => 0
    [total_time] => 0.677605
    [namelookup_time] => 0.181104
    [connect_time] => 0.342955
    [pretransfer_time] => 0.343036
    [size_upload] => 0
    [size_download] => 6579
    [speed_download] => 9709
    [speed_upload] => 0
    [download_content_length] => 6579
    [upload_content_length] => 0
    [starttransfer_time] => 0.515733
    [redirect_time] => 0
    [expires] => Wed, 23 Nov 2011 15:49:24 GMT
)

我想使用 [expires] => Wed, 23 Nov 2011 15:49:24 GMT 标头而不是使用该 if 语句 (file_exists($filename) && (filemtime($filename) > time() - 30)) { 的 time now 减去 30 秒位,因为它只会在需要时更新缓存。

但我不知道该怎么做。

【问题讨论】:

    标签: php caching curl http-headers cache-control


    【解决方案1】:

    你可以touch()strtotime返回时间戳的xml文件,
    示例:-

    date_default_timezone_set('Asia/Singapore'); // replace to your timezone
    $time = strtotime('Wed, 23 Nov 2011 15:49:24 GMT');
    // after file_put_contents
    // call this to change the time
    touch($filename, $time);
    

    【讨论】:

    • 然后对照当前时间检查上次修改文件的时间?
    • 是的,目的是将filemtime设置为与过期日期相同
    • 好的,虽然我收到了这个错误...警告:touch() 期望参数 2 很长,给定字符串
    • 这是它返回的日期格式 Wed, 23 Nov 2011 16:26:33 +0000
    • 使用strtotime将日期字符串转换为时间戳
    猜你喜欢
    • 2017-10-14
    • 2015-06-24
    • 2016-08-31
    • 2023-03-21
    • 1970-01-01
    • 2021-11-29
    • 1970-01-01
    • 2016-06-29
    • 2012-01-08
    相关资源
    最近更新 更多