<?php
/**
* Exports DOM element results for quick fixes, including defensive checks.
*
* @param DOMNode $node The DOM node to export.
* @param string $prefix Optional prefix for the exported properties.
* @return string A string containing PHP code representing the DOM element's properties.
*/
function exportDomElement(DOMNode $node, string $prefix = ''): string
{
$output = '';
// Defensive check: Ensure the node is valid.
if (!$node) {
return '// Invalid DOM node.';
}
// Output the node's attributes.
if ($attributes = $node->attributes) {
foreach ($attributes as $attribute) {
$output .= "\t$prefix \$" . $attribute->name . " = '" . $attribute->value . "';\n";
}
}
// Output the node's properties.
if ($node->hasAttributes() || $node->hasChildNodes()) { // Only show properties if there are attributes or children
foreach ($node->attributes as $attribute) {
$output .= "\t$prefix \$" . $attribute->name . " = '" . $attribute->value . "';\n";
}
}
if ($node->hasChildNodes()) {
foreach ($node->childNodes as $childNode) {
$childName = $childNode->nodeName;
$output .= "\t$prefix \$" . $childName . " = " . exportDomElement($childNode, $prefix . '$') . ";\n"; // Recursive call for child nodes
}
}
return $output;
}
// Example usage:
if (isset($_GET['dom_id']) && is_numeric($_GET['dom_id'])) {
$domId = (int)$_GET['dom_id'];
// Load the DOM document (replace with your actual DOM loading mechanism)
$dom = new DOMDocument();
$dom->loadHTML(file_get_contents('your_html_file.html')); // Replace with your HTML file
$element = $dom->getElementById($domId);
if ($element) {
$code = exportDomElement($element);
echo "<pre>" . $code . "</pre>"; // Output the generated code with formatting
} else {
echo "Element with ID {$domId} not found.";
}
} else {
echo "Please provide a DOM element ID via GET request (e.g., ?dom_id=1).";
}
?>
Add your comment