<?php
/**
* Monitors the state of DOM elements on a webpage.
*
* @param string $url The URL of the webpage to monitor.
* @param array $elements An associative array of element selectors.
* Keys are element names, values are CSS selectors.
* @param int $retry_interval The time in seconds to wait between retries.
* @param int $max_retries The maximum number of retry attempts.
*/
function monitorDOM($url, array $elements, int $retry_interval = 5, int $max_retries = 3) {
for ($retry = 0; $retry < $max_retries; $retry++) {
try {
// Fetch the webpage content
$html = file_get_contents($url);
if ($html === false) {
error_log("Failed to fetch URL: $url");
return; // Exit if URL fetch fails
}
// Create a DOMDocument object
$dom = new DOMDocument();
@$dom->loadHTML($html); // Suppress warnings for malformed HTML
// Check the state of each element
foreach ($elements as $element_name => $selector) {
$element = $dom->querySelector($selector);
if ($element) {
echo "$element_name: Element found.\n";
} else {
echo "$element_name: Element not found.\n";
}
}
return; // Exit if all elements are found (or checked)
} catch (Exception $e) {
error_log("Error: " . $e->getMessage());
if ($retry < $max_retries - 1) {
echo "Retrying in $retry_interval seconds...\n";
sleep($retry_interval);
} else {
echo "Monitoring failed after $max_retries retries.\n";
}
}
}
}
// Example Usage:
// Define the URL and the elements to monitor
$url = 'https://www.example.com';
$elements = [
'title' => 'h1',
'paragraph' => 'p',
'link' => 'a[href]' // Example: check for links with href attribute
];
// Monitor the DOM with a 5-second retry interval and 3 retries
monitorDOM($url, $elements, 5, 3);
?>
Add your comment