简体   繁体   中英

Handle the warnings and notices in foreach loop

I have an array

   $array = [$element1,$element2,$element3...];

I have a php script which does particular tasks(Scraping) on each element of the array

foreach($array as $element){
 //scrape data for each element
  }

This script throws many errors, I want to know for which particular element of the array it is throwing those errors If I run the script in the browser I can simply echo the element name, Something like this

foreach($array as $element){
  echo $element;
  //scrape data for element
  }

So by the above method, I can know which element is throwing the error, Because the element name will print out on the screen before the errors.

But I want to run the script via cron, So i think the only possible way to track the errors is to return an array of errors in the end of the script (and send that in JSON form via email)

For example: if the script throws errors for element3 and element5.. it should return an array in the end of the script

$errors_array = [element3=> ['warning:...','notice:...'], element5=>['warning:...']]

I think I can use this array to get notified about the errors via email (or dump these errors in some file)

Thanks

If I run the script in the browser I can simply echo the element name ... But I want to run the script via cron, So i think the only possible way to track the errors is to return an array of errors in the end of the script

You can very easily capture exactly the same output you would be sending to the browser into a file when you run it under cron. The trick is that you need to redirect both "Standard Error" and "Standard Output" to the same file. The command (which you can test by running manually on the command-line) will look something like this:

php /path/to/my/script.php some args 2>&1 >/path/to/my/output.log

The >file part is redirecting standard output; the 2>&1 adds standard error into the same output file.

You can enable the error reporting in PHP

error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

And send the error logs, you can use them.

else if you want to customized error log

You can use error_get_last() this gives you the last error.

foreach($array as $element){
  $error_arr = error_get_last();
 //log error in the file and flush on next iterator
  error_clear_last();
}

Or use the error reporting tool like sentry which will send you error + current var values to your email.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM