我试图替换字符串中的视频链接--这是我的代码。
$doc = new DOMDocument();
$doc->loadHTML($content);
foreach ($doc->getElementsByTagName("a") as $link)
{
$url = $link->getAttribute("href");
if(strpos($url, ".flv"))
{
echo $link->outerHTML();
}
}
不幸的是, outerHTML
当我试图获取完整的超链接的html代码时,就无法正常工作,如 <a href='http://www.myurl.com/video.flv'></a>
有什么办法可以实现这一点?
在PHP 5.3.6中,你可以将一个节点传递给 saveHtml
例如
$domDocument->saveHtml($nodeToGetTheOuterHtmlFrom);
以前的PHP版本没有实现这种可能性。你必须使用 saveXml()
但这将创建符合XML的标记。如果是一个 <a>
元素,但这不应该是一个问题。
请看 http:/blog.gordon-oheim.biz2011-03-17-The-DOM-Goodie-in-PHP-5.3.6。
你可以在用户笔记中找到几个命题。DOM部分 的PHP手册。
例如,这里有一个由 智慧 :
<?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;
}
?>
最好的解决方案是定义自己的函数,它将返回你的 outerhtml。
function outerHTML($e) {
$doc = new DOMDocument();
$doc->appendChild($doc->importNode($e, true));
return $doc->saveHTML();
}
的函数,而不是在你的代码中使用
echo outerHTML($link);
将一个带有href的文件改名为link.html或link.html,比如说google.comfly.html,里面有flv,或者将flv改成wmv等你想要的href,如果有其他href,它也会把它们捡起来。
<?php
$contents = file_get_contents("links.html");
$domdoc = new DOMDocument();
$domdoc->preservewhitespaces=“false”;
$domdoc->loadHTML($contents);
$xpath = new DOMXpath($domdoc);
$query = '//@href';
$nodeList = $xpath->query($query);
foreach ($nodeList as $node){
if(strpos($node->nodeValue, ".flv")){
$linksList = $node->nodeValue;
$htmlAnchor = new DOMElement("a", $linksList);
$htmlURL = new DOMAttr("href", $linksList);
$domdoc->appendChild($htmlAnchor);
$htmlAnchor->appendChild($htmlURL);
$domdoc->saveHTML();
echo ("<a href='". $node->nodeValue. "'>". $node->nodeValue. "</a><br />");
}
}
echo("done");
?>