2013-04-11 42 views
0

我正在編寫一個應用程序,它使用.php腳本來使用twitter搜索API獲取推文。 請參見下面的代碼:處理錯誤file_get_contents

<?php 
$hashtag = 'hashtag'; // We search Twitter for the hashtag 
$show = 25; // And we want to get 25 tweets 
// Local path 
$cacheFile = '../../_data/tweets.json.cache'; // A cachefile will be placed in _data/ 


$json = file_get_contents("http://search.twitter.com/search.json?result_type=recent&rpp=$show&q=%23" . $hashtag. "%20-RT") or die("Could not get tweets"); 
$fp = fopen($cacheFile, 'w'); 
fwrite($fp, $json); 
fclose($fp); 
?> 

我的問題是,我想確保運行此腳本沒有失敗,或者如果它失敗,至少不會繼續循環。

該腳本將每1分鐘自動運行一次。 有人會知道在這裏處理錯誤的好方法嗎?

TL; DR:如何處理我的代碼中的錯誤?

+0

怎麼樣異常處理... http://www.w3schools.com/php/php_exception.asp – 2013-04-11 11:55:05

+0

這是最好的回答可以幫助你... http://stackoverflow.com/questions/3431169 /好的錯誤處理與文件獲取內容?rq = 1 – 2013-04-11 11:57:28

回答

2

在簡單的情況下,使用'@'前綴作爲函數。它可以抑制顯示中的錯誤。 Read More Here

<?php 
$hashtag = 'hashtag'; // We search Twitter for the hashtag 
$show = 25; // And we want to get 25 tweets 
$cacheFile = '../../_data/tweets.json.cache'; // A cachefile will be placed in _data/ 
$json = @file_get_contents("http://search.twitter.com/search.json?result_type=recent&rpp=$show&q=%23" . $hashtag . "%20-RT"); 
if (!empty($json)) { 
    $fp = fopen($cacheFile, 'w'); 
    fwrite($fp, $json); 
    fclose($fp); 
} else { 
    echo "Could not get tweets"; 
    exit; 
} 
?> 
+0

謝謝,現在我可以安然入睡,知道我的代碼不會自爆。 – Parrotmaster 2013-04-11 12:07:23