2016-03-09 100 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);