tags:

views:

41

answers:

2

How can I loop trought an array of external websites and not fail catastrophically if one of the websites doesn't respond? Consider the following psuedo code:

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

What i want to happen is to try and load page, if it doesn't respond then skip to the next url in the list. The problem is $title is set to blank. I tried grouping the code in a function but I still can't get the error exception to skip whole blocks of code.

A: 

Your code should work this way (except that "continue" is not needed). I guess the error is somewhere else.

Example:

$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) {
 }
}
stereofrog
A: 

Just a quick note of how I would tackle the problem since I am not sure what your "get_page" function is doing

<?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);
}
?>
houmam
Thanks, I guess the first answer answers the question but the second one is the better way to do it.
breez