Thursday, September 1, 2011

Import Xpath Query NodeList To A New XML Document

<?php

$doc = new DOMDocument();
$doc->loadxml($xml); //XML STRING
$xpath = new DOMXpath($doc);
$xpathResults = $xpath->query(""); //YOUR QUERY
$nodes = $xpathResults->length;

if($nodes > 0)
{
 $newDom = new DOMDocument('1.0','UTF-8');
 $root = $newDom->createElement('root');
 $root = $newDom->appendChild($root);
 
 foreach ($xpathResults as $domElement)
 {
  $domNode = $newDom->importNode($domElement, true);
  $root->appendChild($domNode);
  $newXML = $newDom->saveXML();     
 }   
 header("Content-type: application/xml");
 echo $newXML;
} 

?>