Replace Tag in HTML with DOMDocument

后端 未结 2 1307
攒了一身酷
攒了一身酷 2021-01-18 17:51

I\'m trying to edit html tags with DOMDocument::loadHTML in php. The html data is a part of html and not the whole page. I followed what this page (PHP - DOMDocument - need

相关标签:
2条回答
  • 2021-01-18 18:24

    Another way with paquettg/php-html-parser (didn't find the way to change name, so had to use hack with re-binding $this):

    use PHPHtmlParser\Dom;
    use PHPHtmlParser\Dom\HtmlNode;
    
    $dom = new Dom;
    $dom->load($text);
    /** @var HtmlNode[] $tags */
    foreach($dom->find('pre') as $tag) {
        $changeTag = function() {
            $this->name = 'div';
        };
        $changeTag->call($tag->tag);
    };
    echo (string)$dom;
    
    0 讨论(0)
  • 2021-01-18 18:27

    The problem is the call to replaceChild(). Rather than

    $dom->replaceChild($nodeDiv, $nodePre);
    

    use

    $nodePre->parentNode->replaceChild($nodeDiv, $nodePre);
    

    update

    Here is a working code. Seems there is some issue with replacing multiple nodes (more info here: http://php.net/manual/en/domnode.replacechild.php) so you'll have to use a regressive loop to replace the elements.

    $contents = <<<STR
    <pre>hi</pre>
    <pre>hello</pre>
    <pre>bye</pre>
    STR;
    
    $dom = new DOMDocument;
    @$dom->loadHTML($contents);
    
    $elements = $dom->getElementsByTagName("pre");
    for ($i = $elements->length - 1; $i >= 0; $i --) {
        $nodePre = $elements->item($i);
        $nodeDiv = $dom->createElement("div", $nodePre->nodeValue);
        $nodePre->parentNode->replaceChild($nodeDiv, $nodePre);
    }
    
    0 讨论(0)
提交回复
热议问题