我正在使用下面的代码来解析来自远程网站的定义,根据我的数据库中的用户名。我使用简单的HTML DOM解析器。
如何迭代php错误并继续while循环?
//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"]'
)
}
我while循环将开始生成每个用户名的定义,直到没有发现某些网页导致该停止循环的错误。
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
我的问题是,如何跳过抛出错误的用户名和继续循环?还因为他们有超过500个用户名,这个操作是非常密集的,所以我保存了定义,并且想避免错误被保存到数据库。
在循环中使用try/catch块。 – aynber
@aynber无法捕捉到首先抛出的异常...这是一个简单的警告消息。 – CBroe
PHP致命错误不是例外 – ishegg