2009-11-25 76 views
0

如何循环播放外部网站阵列,并且如果其中一个网站没有响应,不会发生灾难性故障?请看下面的伪代码:故障安全循环槽阵列

$urls = array(list of urls); 
foreach ($urls as $url) { 
    try { 
     $page = get_page($url); 
     $title = $page['title']; 
    } catch(Exception $e) { 
     continue; 
    } 
} 

我希望发生的是尝试和加载页面,如果没有响应,然后跳到列表中的下一个URL。问题是$ title被设置为空白。我尝试在一个函数中对代码进行分组,但我仍然无法获得错误异常以跳过整个代码块。

回答

0

你的代码应该以这种方式工作(除了不需要“继续”)。我猜这个错误是在别的地方。

例子:

$a = array(1, 2, 3, 4); 
foreach($a as $b) { 
try { 
    echo $b; // this line works 
    throw new Exception; 
    echo 'NOT THERE'; // this line won't run 
} catch(Exception $e) { 
} 
} 
0

只是一个快速的注意,因为我不知道你的“get_page”功能是干什么

<?php 

$urls[] = "http://www.google.com"; 
$urls[] = "http://www.lkhfsklhqiouhqwre.com"; 

foreach ($urls as $url) { 
    $handle = fopen($url, "r"); 

    if ($handle) { 
     $contents = stream_get_contents($handle); 
     // process the contents 
    } else { 
     echo "$url Failed to load\n"; 
    } 
    fclose($handle); 
} 
?> 
+0

谢谢,我将如何解决这个问题,我想第一个答案回答这个问题,但第二个是更好的方法。 – breez 2009-11-25 14:43:48