如何返回 DOMDocument 的外部 html? [英] How to return outer html of DOMDocument?
问题描述
我正在尝试替换字符串中的视频链接 - 这是我的代码:
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();
}
}
不幸的是,当我尝试获取像 <a href='http://www.myurl.com 这样的完整超链接的 html 代码时,
outerHTML
不起作用/video.flv'>
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?
推荐答案
从 PHP 5.3.6 开始,您可以将节点传递给 saveHtml
,例如
As of PHP 5.3.6 you can pass a node to saveHtml
, e.g.
$domDocument->saveHtml($nodeToGetTheOuterHtmlFrom);
以前版本的 PHP 没有实现这种可能性.您必须使用 saveXml()
,但这会创建符合 XML 的标记.对于 元素,这应该不是问题.
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.
参见 http://blog.gordon-oheim.biz/2011-03-17-The-DOM-Goodie-in-PHP-5.3.6/
这篇关于如何返回 DOMDocument 的外部 html?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!