Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return outer html of DOMDocument?

Tags:

dom

php

outerhtml

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?

like image 986
Fuxi Avatar asked Mar 23 '11 12:03

Fuxi


People also ask

What does outer HTML do?

outerHTML. The outerHTML attribute of the Element DOM interface gets the serialized HTML fragment describing the element including its descendants. It can also be set to replace the element with nodes parsed from the given string.

How do I access outerHTML?

Using jQuery With jQuery, you can access the outerHTML attribute of HTML using the $(selector). prop() or $(selector). attr() method.


2 Answers

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/

like image 60
Gordon Avatar answered Oct 01 '22 03:10

Gordon


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;
}
?> 
like image 44
Pascal MARTIN Avatar answered Oct 01 '22 03:10

Pascal MARTIN