Struggling with simple DOM/XPath usage...

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

Threaded View
Hi All,

I have a task that should be very simple but I'm running into trouble.  All
I want to do is query a document using XPath, and save the resulting XML in
a string.  Here's that I am trying (PHP5):

// $xml has the entire XML document in it; I included it for reference at
the end of the document
$dom = new DOMDocument();

$xpath = new DOMXPath($dom);
$query = "//xml/page[attribute::name='other']";
$result = $xpath->query($query);

foreach ($result as $node)
    //echo $node->saveXML(); // Bombs with an error, as saveXML is not a
method of $node
    $page = new DOMDocument();
    echo $page->saveXML(); // The XML document it prints is nothing but the
xml declaration (<?xml ... ?>)
    $s = simplexml_import_dom($node);
    echo $s->asXML();  // This works - I get a valid piece of XML back,
which tells me that my XPath query must be working (right?)

I'd rather do everything using DOM at this point, since SimpleXML is still
in the experimental stage.  I'd also like to know the DOM way of doing this.
Can someone clue me in?  What am I doing wrong?

**** XML document:
<?xml version="1.0" encoding="iso-8859-1" ?>
 <page name='landing'>
  <dummyTag>Just for testing</dummyTag>
  <owner>John Brown</owner>
 <page name='other'>
  <dummyTag>More testing tags</dummyTag>
  <owner>John Smith</owner>

Re: Struggling with simple DOM/XPath usage...

I think I got it... looks like what I have to do is replace the line that
was $page->importNode($node) with::

    $importedNode = $page->importNode($node,true);

Then I can save the XML to a string by doing:

    $resultXML = $page->saveXML();

This seems a bit "long-winded" though... is this the proper way to do what I
am trying to accomplish?

Also, apologies for not setting FUT.  It should be set to comp.lang.php now.


Site Timeline