1. <?php
  2. /**
  3. * Exports DOM element results for quick fixes, including defensive checks.
  4. *
  5. * @param DOMNode $node The DOM node to export.
  6. * @param string $prefix Optional prefix for the exported properties.
  7. * @return string A string containing PHP code representing the DOM element's properties.
  8. */
  9. function exportDomElement(DOMNode $node, string $prefix = ''): string
  10. {
  11. $output = '';
  12. // Defensive check: Ensure the node is valid.
  13. if (!$node) {
  14. return '// Invalid DOM node.';
  15. }
  16. // Output the node's attributes.
  17. if ($attributes = $node->attributes) {
  18. foreach ($attributes as $attribute) {
  19. $output .= "\t$prefix \$" . $attribute->name . " = '" . $attribute->value . "';\n";
  20. }
  21. }
  22. // Output the node's properties.
  23. if ($node->hasAttributes() || $node->hasChildNodes()) { // Only show properties if there are attributes or children
  24. foreach ($node->attributes as $attribute) {
  25. $output .= "\t$prefix \$" . $attribute->name . " = '" . $attribute->value . "';\n";
  26. }
  27. }
  28. if ($node->hasChildNodes()) {
  29. foreach ($node->childNodes as $childNode) {
  30. $childName = $childNode->nodeName;
  31. $output .= "\t$prefix \$" . $childName . " = " . exportDomElement($childNode, $prefix . '$') . ";\n"; // Recursive call for child nodes
  32. }
  33. }
  34. return $output;
  35. }
  36. // Example usage:
  37. if (isset($_GET['dom_id']) && is_numeric($_GET['dom_id'])) {
  38. $domId = (int)$_GET['dom_id'];
  39. // Load the DOM document (replace with your actual DOM loading mechanism)
  40. $dom = new DOMDocument();
  41. $dom->loadHTML(file_get_contents('your_html_file.html')); // Replace with your HTML file
  42. $element = $dom->getElementById($domId);
  43. if ($element) {
  44. $code = exportDomElement($element);
  45. echo "<pre>" . $code . "</pre>"; // Output the generated code with formatting
  46. } else {
  47. echo "Element with ID {$domId} not found.";
  48. }
  49. } else {
  50. echo "Please provide a DOM element ID via GET request (e.g., ?dom_id=1).";
  51. }
  52. ?>

Add your comment