简体   繁体   中英

Using DomElement to set [class] attribute for AMP html

Is there anyway around ->setAttribute not allowing me to set an attribute named [class] ? I have the following code:

    $success = $doc->createElement('span', 'You have been successfully subscribed');
    $success->setAttribute('class', 'hide');
    $success->setAttribute('[class]', 'ampState.success'); // error here
    $form->appendChild($success);

But when attempting to run this, I get

PHP Fatal error:  Uncaught DOMException: Invalid Character Error in <path>

Is there a lower level manually method I can use to set this attribute?

The workaround I ended up using involved creating a pseudo-tag, which I could str_replace after:

$success = $doc->createElement('span', 'You have been successfully subscribed');
$success->setAttribute('class', 'hide');

// [class] => pseudo-class
$success->setAttribute('pseudo-class', 'ampState.success'); 

$form->appendChild($success);

Then at the very end, I create generate all my HTML and perform a str-replace on that pseudo class to change it back:

// get all HTML inside <body></body>
$body = $doc->getElementsByTagName('body')->item(0);
foreach($body->childNodes as $childNode)
{
    $innerHTML .= $childNode->ownerDocument->saveHTML($childNode);
}

// replace pseudo-class with [class]
$innerHTML = str_replace('pseudo-class', '[class]', $innerHTML);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM