简体   繁体   中英

How to iterate over php error and continue while loop?

I am using the following code to parse definitions from a remote website , according to the usernames in my database. I am using simple html dom parser.

//database connection
include 'db.php';
//display errors
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
include 'simple_html_dom.php';

//select usernames order alphabetically
$row = mysqli_query($conn, "SELECT user_name FROM (
  SELECT * 
  FROM store 
  ORDER BY user_id DESC) 
  AS store ORDER BY user_id ASC");

//echo out definitions of usernames
while($lastusers = mysqli_fetch_array($row)) {
    echo '<br>' . $lastusers["user_name"];
    echo '<br>Definition:<br>';
    $html = file_get_html("https://www.merriam-webster.com/dictionary/" . $lastusers["user_name"]);
    $title = $html->find("div.card-primary-content", 0)->innertext;
    echo $title;

    //save definitions to corresponding username 
    $save = mysqli_query($conn, 'UPDATE  store
    SET     def = $title,
    WHERE   user_name = $lastusers["user_name"]'
    )
}

My while loop will begin to generate the definitions per username , until certain pages are not found resulting in an error that stops the loop.

Warning: file_get_contents( https://www.merriam-webster.com/dictionary/colourings ): failed to open stream: HTTP request failed! HTTP/1.0 404 Not Found in /app/simple_html_dom.php on line 75 Fatal error: Call to a member function find() on boolean in /app/test.php on line 18

My question is how to skip over the username that throws the error and continue the loop? Also because their are over 500 usernames , this operation is very intensive , so i'm saving the definitions , and would like to avoid the errors being saved to the database.

You can suppress the warning like shown in the following link

How can I handle the warning of file_get_contents() function in PHP?

Or an other alternative is to write a custom error handler. See this link

PHP: How to use set_error_handler() to properly deal with all errors except notices?

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