【问题标题】:Use curl instead of file_get_contents in function在函数中使用 curl 而不是 file_get_contents
【发布时间】:2016-06-23 23:26:45
【问题描述】:

在我用于加载和存储 xml-feed 的代码下方。重要的是超时,以防提要离线或响应缓慢。

一些用户没有启用 file_get_contents。我正在寻找一种将其更改为 curl 或进行检查并使用已启用的方法的方法。并且不会失去设置超时的功能。有什么想法吗?

    function feeder()
    {
    $cache_time = 3600 * 12; // 12 hours
    $cache_file = plugin_dir_path(__FILE__) . '/cache/feed.xml';
    $timedif = @(time() - filemtime($cache_file));
    $fc_xml_options = get_option('fc_xml_options');
    $xml_feed = $fc_xml_options['feed'];

    // remove white space(s) and/or space(s) from connector code

    $xml_feed = str_replace(' ', '', $xml_feed);
    $xml_feed = preg_replace('/\s+/', '', $xml_feed);
    if (file_exists($cache_file) && $timedif < $cache_time)
        {
        $string = file_get_contents($cache_file);
        }
      else
        {
        // set a time-out (5 sec) on fetch feed
        $xml_context = array( 'http' => array(
              'timeout'       => 5,
          ) );
        $pure_context = stream_context_create($xml_context);

        $string = file_get_contents($xml_feed, false, $pure_context);
        if ($f = @fopen($cache_file, 'w'))
            {
            fwrite($f, $string, strlen($string));
            fclose($f);
            }
        }

【问题讨论】:

  • 开始翻译?我们修复代码,我们不会为您翻译/重写它......如果 f_g_c() 不可用,您可能要考虑 curl 也不可用。

标签: php wordpress file file-get-contents


【解决方案1】:

您可以使用 curl 读取本地文件。只需将url更改为以file://为前缀的文件路径

    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL, "file://full_path_to_file"); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    // $output contains the output string 
    $output = curl_exec($ch);  
    curl_close($ch);

【讨论】:

    猜你喜欢
    • 2012-01-22
    • 2013-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-08
    • 1970-01-01
    • 2014-09-23
    相关资源
    最近更新 更多