1. <?php
  2. /**
  3. * Retries an HTML page retrieval operation.
  4. *
  5. * @param string $url The URL of the HTML page.
  6. * @param int $maxRetries The maximum number of retries.
  7. * @param int $retryDelay The delay between retries in seconds.
  8. * @return string|false The HTML content if successful, false otherwise.
  9. */
  10. function retryHtmlPage(string $url, int $maxRetries = 3, int $retryDelay = 5): string|false
  11. {
  12. $retries = 0;
  13. while ($retries < $maxRetries) {
  14. try {
  15. // Fetch the HTML content.
  16. $html = file_get_contents($url);
  17. if ($html !== false) {
  18. return $html; // Success!
  19. } else {
  20. $retries++;
  21. if ($retries < $maxRetries) {
  22. sleep($retryDelay);
  23. } else {
  24. return false; // All retries failed.
  25. }
  26. }
  27. } catch (Exception $e) {
  28. $retries++;
  29. if ($retries < $maxRetries) {
  30. sleep($retryDelay);
  31. } else {
  32. return false; // All retries failed.
  33. }
  34. }
  35. }
  36. return false; // Should not reach here if retry logic is correct.
  37. }
  38. /**
  39. * Example usage:
  40. * @param string $url
  41. * @return string|false
  42. */
  43. function getHtmlData(string $url): string|false {
  44. $html = retryHtmlPage($url);
  45. return $html;
  46. }
  47. ?>

Add your comment