首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >更改php outerHTML的DOMElement?

更改php outerHTML的DOMElement?
EN

Stack Overflow用户
提问于 2020-04-28 17:13:31
回答 1查看 326关注 0票数 0

如何使用PHP类更改元素的outerHtml?确保没有使用任何第三方库,比如简单的PHP、Dom或其他。

例如:我想做这样的事情。

代码语言:javascript
复制
$dom = new DOMDocument;
$dom->loadHTML($html);  
$tag = $dom->getElementsByTagName('h3');
foreach ($tag as $e) {
 $e->outerHTML = '<h5>Hello World</h5>';
}

libxml_clear_errors();
$html = $dom->saveHTML();
echo $html;

输出应该是这样的:

代码语言:javascript
复制
Old Output: <h3>Hello World</h3>
But I need this new output: <p>Hello World</p>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-04-28 17:45:23

您可以在新节点中创建元素内容和属性的副本(使用所需的新名称),并使用函数replaceChild()

当前代码只适用于简单元素(节点内的文本),如果有嵌套元素,则需要编写递归函数。

代码语言:javascript
复制
$dom = new DOMDocument;
$dom->loadHTML($html);  

$titles = $dom->getElementsByTagName('h3');
for($i = $titles->length-1 ; $i >= 0 ; $i--)
{
    $title = $titles->item($i);
    $titleText = $title->textContent ; // get original content of the node

    $newTitle = $dom->createElement('h5'); // create a new node with the correct name
    $newTitle->textContent = $titleText ; // copy the content of the original node

    // copy the attribute (class, style, ...)
    $attributes = $title->attributes ;
    for($j = $attributes->length-1 ; $j>= 0 ; --$j)
    {
        $attributeName = $attributes->item($j)->nodeName ;
        $attributeValue = $attributes->item($j)->nodeValue ;

        $newAttribute = $dom->createAttribute($attributeName);
        $newAttribute->nodeValue = $attributeValue ;

        $newTitle->appendChild($newAttribute);
    }


    $title->parentNode->replaceChild($newTitle, $title); // replace original node per our copy
}


libxml_clear_errors();
$html = $dom->saveHTML();
echo $html;
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61485985

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档