How to get html code of DOMElement node? [duplicate]
Asked Answered
I

2

43

I have this html code:

<html>
    <head>
    ...
    </head>
<body>
    <div>
    <div class="foo" data-type="bar">
        SOMECONTENTWITHMORETAGS
    </div>
    </div>
</body>

I already can get the "foo" element (but only its content) with this function:

private function get_html_from_node($node){
  $html = '';
  $children = $node->childNodes;

  foreach ($children as $child) {
    $tmp_doc = new DOMDocument();
    $tmp_doc->appendChild($tmp_doc->importNode($child,true));
    $html .= $tmp_doc->saveHTML();
  } 
  return $html;
}

But I'd like to return all html tags (including its attributes) of DOMElement. How I can do that?

Implausibility answered 16/10, 2012 at 7:43 Comment(5)
If you are trying to get html_from_node class="foo" you are doing it not correct. There is much easy and short way of doing this.Pilotage
Is this helpful? #6366851Venesection
@webbandit I know there is a better way. Please show me!Implausibility
Note: This is not duplicate, as it's asking to return html of DOMElement, not DOMDocument as in other question, and these questions have already different answers.Battista
@Battista hey, it's SO. every question is a duplicate now by definition 🤣Squiffy
B
100

Use the optional argument to DOMDocument::saveHTML: this says "output this element only".

return $node->ownerDocument->saveHTML($node);

Note that the argument is only available from PHP 5.3.6. Before that, you need to use DOMDocument::saveXML instead. The results may be slightly different. Also, if you already have a reference to the document, you can just do this:

$doc->saveHTML($node);
Beastings answered 16/10, 2012 at 7:51 Comment(9)
This is actually what I need but it's for an WordPress plugin which should work with version 3.4 and this versions requires php 5.2.4.Implausibility
@revaxarts Then use saveXML. The output will be little different...Beastings
u point me to a full example? I don't have a reference of the document in the function only the node and DOMDocument::saveXML($node) is not working same as $node->saveXML($node)Implausibility
@revaxarts The code you'll need is $node->ownerDocument->saveXML($node).Beastings
ok, great thanks! Is there a documentation what is different to saveHTML and which php version is required?Implausibility
@revaxarts See the two PHP manual pages linked in my answer.Beastings
I can't post full code as an answer, but this answer is incorrect. Here's the working code: gist.github.com/komlenic/1374083Squiffy
This answer is incorrect @Squiffy You are a life saver ... your link saved my life.Contrapositive
That code surely does something entirely different, @ClainDsilva.Beastings
T
-11

PHP Simple HTML DOM Parser should do the job!

Tjader answered 16/10, 2012 at 7:52 Comment(1)
At least provide a snippet or use case example next timeHype

© 2022 - 2024 — McMap. All rights reserved.