Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DOMDocument > setAttribute() > bool attribute?

I try to create a PHP-Class which can compress HTML, so I wanted to replace e.g. required="required" with required. But how can I add an bool attribute via DOMDocument?

Code: https://3v4l.org/Ot9th

$doc = new DOMDocument("1.0");
$node = $doc->createElement("input");
$newnode = $doc->appendChild($node);
$newnode->setAttribute("required", '');
var_dump($doc->saveHTML());

Result:

<input required=""></para>

Expected:

<input required></para>
like image 992
Lars Moelleken Avatar asked Aug 08 '26 16:08

Lars Moelleken


1 Answers

PHP's DOMDocument creates a valid XML structure, and according to both XML 1.0 and XML 1.1 - it's not valid to add empty attributes.

Boolean attributes should have their values the same as the name of the attribute.

This is valid:

<input required="required"></para>


This is NOT valid:

<input required></para>

update

The savehtml function validates content based to dtd. According to the xhtml1.0 dtd, this is the list of attributes that are valid as empty attributes:

checked
disabled
readonly
multiple
selected
compact
noshade
declare
ismap
nohref
nowrap

Any other attribute must have a value

like image 94
Dekel Avatar answered Aug 11 '26 05:08

Dekel