Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get innerHTML of DOMNode?

Tags:

dom

php

innerhtml

What function do you use to get innerHTML of a given DOMNode in the PHP DOM implementation? Can someone give reliable solution?

Of course outerHTML will do too.

like image 675
Dawid Ohia Avatar asked Jan 18 '10 15:01

Dawid Ohia


People also ask

How do I get innerHTML in PHP?

php function DOMinnerHTML(DOMNode $element) { $innerHTML = ""; $children = $element->childNodes; foreach ($children as $child) { $innerHTML . = $element->ownerDocument->saveHTML($child); } return $innerHTML; } ?>

How do I get data from innerHTML?

How it works. First, get the <ul> element with the id menu using the getElementById() method. Second, create a new <li> element and add it to the <ul> element using the createElement() and appendChild() methods. Third, get the HTML of the <ul> element using the innerHTML property of the <ul> element.

What does .innerHTML return?

The innerHTML property returns: The text content of the element, including all spacing and inner HTML tags. The innerText property returns: Just the text content of the element and all its children, without CSS hidden text spacing and tags, except <script> and <style> elements.

What can I use instead of innerHTML?

For that reason, it is recommended that instead of innerHTML you use: Element.SetHTML() to sanitize the text before it is inserted into the DOM.


2 Answers

Compare this updated variant with PHP Manual User Note #89718:

<?php  function DOMinnerHTML(DOMNode $element)  {      $innerHTML = "";      $children  = $element->childNodes;      foreach ($children as $child)      {          $innerHTML .= $element->ownerDocument->saveHTML($child);     }      return $innerHTML;  }  ?>  

Example:

<?php  $dom= new DOMDocument();  $dom->preserveWhiteSpace = false; $dom->formatOutput       = true; $dom->load($html_string);   $domTables = $dom->getElementsByTagName("table");   // Iterate over DOMNodeList (Implements Traversable) foreach ($domTables as $table)  {      echo DOMinnerHTML($table);  }  ?>  
like image 85
Haim Evgi Avatar answered Sep 18 '22 09:09

Haim Evgi


Here is a version in a functional programming style:

function innerHTML($node) {     return implode(array_map([$node->ownerDocument,"saveHTML"],                               iterator_to_array($node->childNodes))); } 
like image 36
trincot Avatar answered Sep 20 '22 09:09

trincot