使用DomElement为AMP html设置[class]属性

时间:2018-04-25 17:59:22

标签: php dom amp-html

->setAttribute周围是否有我不能设置名为[class]的属性?我有以下代码:

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

但是在尝试运行时,我得到了

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

我可以使用较低级别的手动方法来设置此属性吗?

1 个答案:

答案 0 :(得分:0)

我最终使用的变通方法涉及创建一个伪标签,我可以 str_replace 之后:

$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);

然后在最后,我创建生成我的所有HTML并在该伪类上执行str替换以将其更改回来:

// 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);