Struggling with simple DOM/XPath usage...

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Joshua Beall

    Struggling with simple DOM/XPath usage...

    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();
    $dom->loadXML($xml );

    $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();
    $page->importNode($no de);
    echo $page->saveXML(); // The XML document it prints is nothing but the
    xml declaration (<?xml ... ?>)
    $s = simplexml_impor t_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" ?>
    <xml>
    <page name='landing'>
    <dummyTag>Jus t for testing</dummyTag>
    <owner>John Brown</owner>
    </page>
    <page name='other'>
    <dummyTag>Mor e testing tags</dummyTag>
    <owner>John Smith</owner>
    </page>
    </xml>


  • Joshua Beall

    #2
    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($no de) with::

    $importedNode = $page->importNode($no de,true);
    $page->appendChild($i mportedNode);

    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.

    -jb


    Comment

    Working...