次のコードを使用して、リモートWebサイトの定義をデータベースのユーザー名に基づいて解析しています。私は単純な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