故障安全循环通过网址数组

时间:2009-11-25 11:14:16

标签: php

如果其中一个网站没有响应,我如何在一系列外部网站中循环而不是灾难性的失败?请考虑以下伪代码:

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

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

2 个答案:

答案 0 :(得分: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) {
 }
}

答案 1 :(得分: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);
}
?>