如何修改给定PHP循环代码,统计成功与错误的总次数?
Solution to Track Success and Error Counts in Your PHP Script
Got it, let's tweak your code to properly track and output the total success and error counts you need. First, let's fix a couple of small issues in your original code, then add the counting functionality step by step:
- Fix the loop increment bug: Your current code has
$i++both in theforloop declaration and at the end of the loop body. This makes each iteration increment$itwice, so your loop will only run 51 times instead of 101. We'll remove the extra$i++inside the loop. - Fix the
preg_matchpattern: PHP'spreg_matchrequires delimiters (like/) around the regex pattern to work correctly—your original pattern is missing these. - Add count trackers: We'll initialize two variables to keep tabs on how many times we get a success vs. error.
- Output final stats: After the loop finishes, we'll print the totals in the exact format you requested.
Here's the revised code:
<?php error_reporting(E_ALL ^ (E_NOTICE | E_WARNING)); // Initialize counters to track success and error counts $successCount = 0; $errorCount = 0; for ($i = 0; $i <= 100; $i++) { $url = "site.com"; $h = [ "Accept-Language: en-US,en;q=0.8", ]; $ch = curl_init(); curl_setopt($ch, CURLOPT_HTTPHEADER, $h); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $x = curl_exec($ch); curl_close($ch); // Check if the response contains the HTML doctype if (preg_match('/<!DOCTYPE html>/', $x)) { echo "Success\n"; $successCount++; // Increment success counter } else { echo "Error\n"; $errorCount++; // Increment error counter } } // Print the final statistics in your desired format echo "Success {$successCount} times and error {$errorCount} times"; ?>
Quick Notes on Key Changes:
- Counter Variables:
$successCountand$errorCountstart at 0, and we increment them each time we hit a success or error case. - Fixed Loop: Removing the extra
$i++ensures the loop runs exactly 101 times (from 0 to 100 inclusive, which matches your original intent). - Robust Regex: If the target site's doctype has extra whitespace or uses uppercase letters, you can adjust the regex to
/<!DOCTYPE\s+html>/i—theiflag makes it case-insensitive, and\s+accounts for any spaces betweenDOCTYPEandhtml.
If you don't need to see each individual success/error message during the loop, just delete the echo "Success\n"; and echo "Error\n"; lines inside the loop to clean up the output.
内容的提问来源于stack exchange,提问作者Eyus Wap
相关产品推荐
相关产品推荐

