Grab all XML of Node (PHP5)

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
I'm looking for a way to grab *all* XML of a DOM node (in PHP5).
Something like the following, only it doesn't work! Thanks.

/* I want everything (all XHTML) in <div id="hell=">...</div> */

$dom = new domdocument;
@$dom->loadHTMLFile(' ');
$xpath = new domxpath($dom);
$xNodes = $xpath->query("//div[@id='hello']//p/*");
$sText = '';
foreach ($xNodes as $xNode)
    $sText .= $xNode->firstChild->data . ' ';

$sText = strip_tags($sText);
echo 'Result:' . $sText;

Google Blogoscoped

Re: Grab all XML of Node (PHP5)

On Mon, 15 Nov 2004 11:27:55 +0000, Philipp Lenssen wrote:

Quoted text here. Click to load it
{snipped code)

I prefer to use the saveXML method myself, but you may want to use
saveHTML.If you just want the entire node subtree then just isolate the
parent node and save it out, something like

  $text = $xmldom->saveXML($xpath->query('whatever')->item(0));

If you just want the childNodes then I use a function something like this
(assuming we've already ->loaded something into $xmldom)

function xpathContents($xpath,$xmldom)
  #New Xpath Content and query
  $xmlContext = new domXPath($xmldom);
  $nodeset = $parent = $xmlContext->query($xpath);
  if ( $nodeset->length == 0 ) {
    #Return blank if no results, could always "return FALSE" instead
    return "";
  else {
    $result = "";
    #Select first result from $parent set and then select it's children
    foreach ( $parent->item(0)->childNodes as $child) {
      $result .= $xmldom->saveXML($child)
    return $result;

Site Timeline