I have an HTML code where there are attributes like @click
, @autocomplete:change
used by some JS libraries.
When I parse the HTML using DOMDocument, these attributes are removed.
Sample code:
<?php
$content = <<<'EOT'
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head></head>
<body>
<a role="tab" @click="activeType=listingType"></a>
<input type="text" @autocomplete:change="handleAutocomplete">
</body>
</html>
EOT;
// creating new document
$doc = new DOMDocument('1.0', 'utf-8');
$doc->recover = true;
$doc->strictErrorChecking = false;
//turning off some errors
libxml_use_internal_errors(true);
// it loads the content without adding enclosing html/body tags and also the doctype declaration
$doc->LoadHTML($content, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
echo $doc->saveHTML();
?>
Output:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head></head>
<body>
<a role="tab"></a>
<input type="text">
</body>
</html>
If there's no way to make DOMDocument
accept @
in attribute names, we can replace @
with a special string before loadHTML()
, and replace back after saveHTML()
<?php
$content = <<<'EOT'
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head></head>
<body>
<a role="tab" @click="activeType=listingType"></a>
<input type="text" @autocomplete:change="handleAutocomplete">
</body>
</html>
EOT;
// creating new document
$doc = new DOMDocument('1.0', 'utf-8');
$doc->recover = true;
$doc->strictErrorChecking = false;
//turning off some errors
libxml_use_internal_errors(true);
$content = str_replace('@', 'at------', $content);
// it loads the content without adding enclosing html/body tags and also the doctype declaration
$doc->LoadHTML($content, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$html = $doc->saveHTML();
$html = str_replace('at------', '@', $html);
echo $html;
output:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head></head>
<body>
<a role="tab" @click="activeType=listingType"></a>
<input type="text" @autocomplete:change="handleAutocomplete">
</body>
</html>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With