19

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.

2 Answers 2

56

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();
}
Sign up to request clarification or add additional context in comments.

4 Comments

oh thanks dev-null-dweller this is exactly what i needed. this saved lot of time. thank you again.
tnx guy you are realy useful :D
PLease note @dennis answer below this one here for newer PHP versions.
Just testing at my end and it appears the '$cloned = $element->cloneNode(TRUE);' line is unnecessary if you put the $element item in the importNode method as opposed to placing the '$cloned' item as you have.
28

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.