How to return outer html of DOMDocument?

戏子无情 提交于 2019-11-26 00:34:12

问题


I\'m trying to replace video links inside a string - here\'s my code:

$doc = new DOMDocument();
$doc->loadHTML($content);
foreach ($doc->getElementsByTagName(\"a\") as $link) 
{
    $url = $link->getAttribute(\"href\");
    if(strpos($url, \".flv\"))
    {
        echo $link->outerHTML();
    }
}

Unfortunately, outerHTML doesn\'t work when I\'m trying to get the html code for the full hyperlink like <a href=\'http://www.myurl.com/video.flv\'></a>

Any ideas how to achieve this?


回答1:


As of PHP 5.3.6 you can pass a node to saveHtml, e.g.

$domDocument->saveHtml($nodeToGetTheOuterHtmlFrom);

Previous versions of PHP did not implement that possibility. You'd have to use saveXml(), but that would create XML compliant markup. In the case of an <a> element, that shouldn't be an issue though.

See http://blog.gordon-oheim.biz/2011-03-17-The-DOM-Goodie-in-PHP-5.3.6/




回答2:


You can find a couple of propositions in the users notes of the DOM section of the PHP Manual.

For example, here's one posted by xwisdom :

<?php
// code taken from the Raxan PDI framework
// returns the html content of an element
protected function nodeContent($n, $outer=false) {
    $d = new DOMDocument('1.0');
    $b = $d->importNode($n->cloneNode(true),true);
    $d->appendChild($b); $h = $d->saveHTML();
    // remove outter tags
    if (!$outer) $h = substr($h,strpos($h,'>')+1,-(strlen($n->nodeName)+4));
    return $h;
}
?> 



回答3:


The best possible solution is to define your own function which will return you outerhtml:

function outerHTML($e) {
     $doc = new DOMDocument();
     $doc->appendChild($doc->importNode($e, true));
     return $doc->saveHTML();
}

than you can use in your code

echo outerHTML($link); 


来源:https://stackoverflow.com/questions/5404941/how-to-return-outer-html-of-domdocument

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!