2016-03-09 42 views
1

下面我加载和存储xml-feed的代码。重要的是,如果Feed处于脱机状态或响应速度较慢,则超时。使用curl代替函数中的file_get_contents

某些用户没有启用file_get_contents。我正在寻找一种方法来改变这个卷曲或做一个检查,并使用启用。而不是失去功能来设置超时。有任何想法吗?

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); 
      } 
     } 
+1

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

回答

1

您可以使用curl来读取本地文件。只需将网址更改为前缀为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);