Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert part of dom element to string with html tags inside of them

Tags:

im in need of converting part of DOM element to string with html tags inside of them.

i tried following but it prints just a text without tags in side.

$dom = new DOMDocument();
$dom->loadHTMLFile('http://www.pixmania-pro.co.uk/gb/uk/08920684/art/packard-bell/easynote-tm89-gu-015uk.html');
$xpath = new DOMXPath($dom);
$elements=xpath->query('//table');

foreach($elements as $element)
echo $element->nodeValue;

i want all the tags as it is and the content inside tables. can some one help me. it'll be a greate help.

thanks.

like image 949
dakshina11 Avatar asked Dec 25 '10 14:12

dakshina11


People also ask

How do I turn a HTML element into a string?

To convert a HTMLElement to a string with JavaScript, we can use the outerHTML property. const element = document. getElementById("new-element-1"); const elementHtml = element.

How do you make a DOM string?

The createElement() method is used for creating elements within the DOM. It accepts two parameters, a tagName which is a string that defines the type of element to create, and an optional options object that can be used to modify how the element is created.

How do I grab an element from a DOM?

The easiest way to access a single element in the DOM is by its unique ID. You can get an element by ID with the getElementById() method of the document object. In the Console, get the element and assign it to the demoId variable. const demoId = document.


2 Answers

Current solution:

foreach($elements as $element){
    echo $dom->saveHTML($element);
}

Old answer (php < 5.3.6):

  1. Create new instance of DomDocument
  2. Clone node (with all sub nodes) you wish to save as HTML
  3. Import cloned node to new instance of DomDocument and append it as a child
  4. Save new instance as html

So something like this:

foreach($elements as $element){
    $newdoc = new DOMDocument();
    $cloned = $element->cloneNode(TRUE);
    $newdoc->appendChild($newdoc->importNode($cloned,TRUE));
    echo $newdoc->saveHTML();
}
like image 127
dev-null-dweller Avatar answered Sep 29 '22 13:09

dev-null-dweller


With php 5.3.6 or higher you can use a node in DOMDocument::saveHTML:

foreach($elements as $element){
    echo $dom->saveHTML($element);
}
like image 25
dennis Avatar answered Sep 29 '22 14:09

dennis