Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the Inner HTML of a DomElement in PHP [duplicate]

Tags:

dom

php

What's the simplest way to get the innerHTML (tags and all) of a DOMElement using PHP's DOM functions?

like image 916
bgcode Avatar asked Aug 23 '11 03:08

bgcode


People also ask

How do I get innerHTML in PHP?

Code of innerHTML() php // returns a string with the HTML content from a DOMDocument node element ($elm) function innerHTML(DOMNode $elm) { $innerHTML = ''; $children = $elm->childNodes; foreach($children as $child) { $innerHTML .

What is the inner HTML?

The Element property innerHTML gets or sets the HTML or XML markup contained within the element. To insert the HTML into the document rather than replace the contents of an element, use the method insertAdjacentHTML() .

When we use innerHTML in javascript?

The innerHTML property can be used to write the dynamic html on the html document. It is used mostly in the web pages to generate the dynamic html such as registration form, comment form, links etc.


2 Answers

$html = '';
foreach($parentElement->childNodes as $node) {
   $html .= $dom->saveHTML($node);
}

CodePad.

like image 85
alex Avatar answered Sep 20 '22 12:09

alex


Inner HTML

Try approach suggested by @trincot:

$html = implode(array_map([$node->ownerDocument,"saveHTML"], iterator_to_array($node->childNodes)));

Outer HTML

Try:

$html = $node->ownerDocument->saveHTML($node);

or in PHP lower than 5.3.6:

$html = $node->ownerDocument->saveXML($node);
like image 34
kenorb Avatar answered Sep 20 '22 12:09

kenorb