Lars Moelleken
Lars Moelleken

Reputation: 728

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>

Upvotes: 3

Views: 956

Answers (2)

Lars Moelleken
Lars Moelleken

Reputation: 728

Ok, I could solve the problem with usage of random_bytes() and str_replace() ...

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

$rand = md5(random_bytes(16));
$doc = new DOMDocument("1.0");
$node = $doc->createElement("input");
$newnode = $doc->appendChild($node);
$newnode->setAttribute("required", 'delete-this' . $rand);

var_dump(
  str_replace(
    array('="delete-this' . $rand . '"'), 
    array(''), 
    $doc->saveHTML()
  )
);

Upvotes: 0

Dekel
Dekel

Reputation: 62556

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

Upvotes: 2

Related Questions