1. <?php
  2. /**
  3. * Maps fields of DOM elements for routine automation.
  4. *
  5. * @param DOMElement $target The DOM element to map fields from.
  6. * @param array $field_map An associative array mapping field names to DOM element selectors.
  7. * e.g., ['name' => '#name_field', 'email' => 'input[type="email"]']
  8. * @return array An associative array containing the mapped field values. Returns an empty array on error.
  9. */
  10. function mapDomFields(DOMElement $target, array $field_map): array
  11. {
  12. $mapped_values = [];
  13. foreach ($field_map as $field_name => $selector) {
  14. $element = $target->querySelector($selector); // Find the element using the selector
  15. if ($element) {
  16. $mapped_values[$field_name] = $element->value; // Get the element's value
  17. } else {
  18. // Handle the case where the element is not found.
  19. // You can log an error, set a default value, or skip the field.
  20. error_log("Field not found: " . $field_name . " with selector: " . $selector);
  21. $mapped_values[$field_name] = null; // or a default value like ""
  22. }
  23. }
  24. return $mapped_values;
  25. }
  26. /**
  27. * Example usage (demonstration)
  28. */
  29. if (isset($_POST['start_automation'])) { //Checking if the form has been submitted
  30. $targetElement = document->getElementById('automation_form'); // Assuming an element with id 'automation_form'
  31. $fieldMap = [
  32. 'username' => '#username',
  33. 'password' => '#password',
  34. 'submit_button' => '#submit_button'
  35. ];
  36. $mappedData = mapDomFields($targetElement, $fieldMap);
  37. // Process the mapped data (e.g., submit a form)
  38. if (isset($mappedData['submit_button'])) {
  39. $submitButton = $targetElement->querySelector($mappedData['submit_button']);
  40. if ($submitButton) {
  41. $submitButton->click(); //Simulate a click on the button
  42. }
  43. }
  44. }
  45. ?>

Add your comment