1. <?php
  2. /**
  3. * Monitors the state of DOM elements on a webpage.
  4. *
  5. * @param string $url The URL of the webpage to monitor.
  6. * @param array $elements An associative array of element selectors.
  7. * Keys are element names, values are CSS selectors.
  8. * @param int $retry_interval The time in seconds to wait between retries.
  9. * @param int $max_retries The maximum number of retry attempts.
  10. */
  11. function monitorDOM($url, array $elements, int $retry_interval = 5, int $max_retries = 3) {
  12. for ($retry = 0; $retry < $max_retries; $retry++) {
  13. try {
  14. // Fetch the webpage content
  15. $html = file_get_contents($url);
  16. if ($html === false) {
  17. error_log("Failed to fetch URL: $url");
  18. return; // Exit if URL fetch fails
  19. }
  20. // Create a DOMDocument object
  21. $dom = new DOMDocument();
  22. @$dom->loadHTML($html); // Suppress warnings for malformed HTML
  23. // Check the state of each element
  24. foreach ($elements as $element_name => $selector) {
  25. $element = $dom->querySelector($selector);
  26. if ($element) {
  27. echo "$element_name: Element found.\n";
  28. } else {
  29. echo "$element_name: Element not found.\n";
  30. }
  31. }
  32. return; // Exit if all elements are found (or checked)
  33. } catch (Exception $e) {
  34. error_log("Error: " . $e->getMessage());
  35. if ($retry < $max_retries - 1) {
  36. echo "Retrying in $retry_interval seconds...\n";
  37. sleep($retry_interval);
  38. } else {
  39. echo "Monitoring failed after $max_retries retries.\n";
  40. }
  41. }
  42. }
  43. }
  44. // Example Usage:
  45. // Define the URL and the elements to monitor
  46. $url = 'https://www.example.com';
  47. $elements = [
  48. 'title' => 'h1',
  49. 'paragraph' => 'p',
  50. 'link' => 'a[href]' // Example: check for links with href attribute
  51. ];
  52. // Monitor the DOM with a 5-second retry interval and 3 retries
  53. monitorDOM($url, $elements, 5, 3);
  54. ?>

Add your comment