PHP DOM函数从HTML5元素创建DIV ID



我正在使用以下功能将HTML5元素替换为Div ID。

<?php function nonHTML5 ($content){
        $dom = new DOMDocument;
        // Hide HTML5 element errors
        libxml_use_internal_errors(true);
        $dom->loadHTML($content);
        libxml_clear_errors();
        $xp = new DOMXPath($dom);
        // Bring elements into array
        $elements = $xp->query('//*[self::header| self::footer ]
        [not(ancestor::pre) and not(ancestor::code)]');
        // Loop through
        foreach($elements as $element){
            // Replace with 'div' tag
            $newElement = $dom->createElement('div');
            while($element->childNodes->length){
                // Keepup with the child nodes
                $childElement = $element->childNodes->item(0);
                $newElement->appendChild($dom->importNode($childElement, true));
            }
            while($element->attributes->length){
                // Mailtain the length
                $attributeNode = $element->attributes->item(0);
                $newElement->setAttributeNode($dom->importNode($attributeNode));
            }
            $element->parentNode->replaceChild($newElement, $element);
        }
    $content = $dom->saveXML($dom->documentElement);
    return $content;
} ?>

我知道我们可以使用HTMLSHIV,但我想主要针对JavaScript禁用的旧浏览器。

我的挑战:

我无法向其添加ID ="。例如.....

<header>
<h1>I am the header</h1>
</header>

应该成为

<div id ="header">
<h1>I am the header</h1>
</div>

我尝试做......

$newElement = $dom->createElement('div id ="' . $element . '"');

但不起作用。

我的问题

应该正确的代码?

请注意:我不是PHP专家,因此请在您的答案/评论中描述一点。

这是您可以做到的:

注意:我添加了注释,以便更多澄清,确切的代码每个语句中正在发生的事情。

使用DOM创建具有属性的HTML元素:

<?php 
// Initiate a new DOMDocument
$dom = new DOMDocument();
// Create an element
$div = $dom->createElement("div","HERE DIV CONTENTS"); 
// Create an attribute i.e id
$divAttr = $dom->createAttribute('id');
// Assign value to your attribute i.e id="value"
$divAttr->value = 'This is an id';
// Add your attribute (id) to your element (div)
$div->appendChild($divAttr);
// Add your element (div) to DOM
$dom->appendChild($div);
// Print your DOM HERE
echo  $dom->saveHTML();
?>

代码输出:

<div id="This is an id">HERE DIV CONTENTS</div>

最新更新