【问题标题】:How to iterate over php error and continue while loop?如何迭代php错误并继续while循环?
【发布时间】:2017-08-22 16:42:17
【问题描述】:

根据我数据库中的用户名,我正在使用以下代码解析来自远程网站的定义。我正在使用简单的 html dom 解析器。

//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 循环将开始为每个 username 生成定义,直到找不到某些页面导致错误停止循环。

警告: 文件获取内容(https://www.merriam-webster.com/dictionary/colourings): 无法打开流:HTTP 请求失败! HTTP/1.0 404 未在 /app/simple_html_dom.php 第 75 行致命错误:调用成员 函数 find() on boolean in /app/test.php 第 18 行

我的问题是如何跳过引发错误的用户名并继续循环?也因为他们有超过 500 个用户名,这个操作非常密集,所以我正在保存定义,并希望避免将错误保存到数据库中。

【问题讨论】:

  • 在循环中使用 try/catch 块。
  • @aynber 无法捕捉到什么不会引发异常...这是一条简单的警告消息。
  • PHP 中的致命错误不是例外
  • @CBroe 哦,对,好点。
  • 您还可以使用@ 抑制 PHP 中的错误(尽管我不建议这样做) - 有关错误抑制的更多信息,请参阅此问题:stackoverflow.com/questions/136899/…

标签: php database mysqli


【解决方案1】:

您可以抑制警告,如下面的链接所示

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

或者另一种选择是编写自定义错误处理程序。看这个链接

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-11
    相关资源
    最近更新 更多