<?php
/**
* Maps fields of DOM elements for routine automation.
*
* @param DOMElement $target The DOM element to map fields from.
* @param array $field_map An associative array mapping field names to DOM element selectors.
* e.g., ['name' => '#name_field', 'email' => 'input[type="email"]']
* @return array An associative array containing the mapped field values. Returns an empty array on error.
*/
function mapDomFields(DOMElement $target, array $field_map): array
{
$mapped_values = [];
foreach ($field_map as $field_name => $selector) {
$element = $target->querySelector($selector); // Find the element using the selector
if ($element) {
$mapped_values[$field_name] = $element->value; // Get the element's value
} else {
// Handle the case where the element is not found.
// You can log an error, set a default value, or skip the field.
error_log("Field not found: " . $field_name . " with selector: " . $selector);
$mapped_values[$field_name] = null; // or a default value like ""
}
}
return $mapped_values;
}
/**
* Example usage (demonstration)
*/
if (isset($_POST['start_automation'])) { //Checking if the form has been submitted
$targetElement = document->getElementById('automation_form'); // Assuming an element with id 'automation_form'
$fieldMap = [
'username' => '#username',
'password' => '#password',
'submit_button' => '#submit_button'
];
$mappedData = mapDomFields($targetElement, $fieldMap);
// Process the mapped data (e.g., submit a form)
if (isset($mappedData['submit_button'])) {
$submitButton = $targetElement->querySelector($mappedData['submit_button']);
if ($submitButton) {
$submitButton->click(); //Simulate a click on the button
}
}
}
?>
Add your comment