-1

I am pulling data from a 3rd party web service and when the api goes under maintenance the json document no longer has the same structure (but is still a valid json document). So when I go to parse, I get an error: "Invalid argument supplied for foreach()" Makes sense, but how do I test for this and then call a separate function to log the error with the contents of the json document?

I tried adding set_error_handler("customError"); and that works but I don't know how to access the contents of $response or $json from the error function

$response = file_get_contents($url);
$json = json_decode($response, TRUE);

foreach($json['workers'] as $item) {
    echo $item['address']; //address does not exist when in maintenance mode!
}

function customError($errno, $errstr) {
    $link=Connection();
    echo "<b>Error:</b> [$errno] $errstr ";
    $sql="Insert into myErrors (response, description) values ('".$response."','.$errstr.');";
    //echo $sql;
    $result = mysqli_query( $link,$sql) or die('Error; ' . mysqli_error($link));
  }
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
Jay
  • 162
  • 1
  • 1
  • 9
  • 2
    Check whether `$json['workers']` exists before the `foreach` – Barmar Feb 11 '21 at 19:05
  • `echo $response;` And show us the result if its not obvious – RiggsFolly Feb 11 '21 at 19:08
  • 1
    It is a very bad idea to use `die(mysqli_error($conn));` in your code, because it could potentially leak sensitive information. See this post for more explanation: [mysqli or die, does it have to die?](https://stackoverflow.com/a/15320411/1839439) – Dharman Feb 11 '21 at 19:20

1 Answers1

1

Test the result to see if the array exists before trying to loop over it.

$response = file_get_contents($url);
$json = json_decode($response, TRUE);

if (isset($json['workers'])) {
    foreach($json['workers'] as $item) {
            echo $item['address']; //address does not exist when in maintenance mode!
    }
} else {
    // insert something into myErrors table
}
Barmar
  • 741,623
  • 53
  • 500
  • 612