views:

124

answers:

2

Hey all, I have this SimpleXMLElement object with a XML setup similar to the following...

$xml <<< EOX
<books>
    <book>
        <name>ABCD</name>
    </book>
</books>
EOX;

$sx = new SimpleXMLElement( $xml );

Now I have a class named Book that contains info. about each book. The same class can also spit out the book info. in XML format akin the the above (the nested block).. example,

$book = new Book( 'EFGH' );
$book->genXML();

... will generate
<book>
    <name>EFGH</name>
</book>

Now I'm trying to figure out a way by which I can use this generated XML block and append as a child of so that now it looks like... for example..

// Non-existent member method. For illustration purposes only.
$sx->addXMLChild( $book->genXML() );    

...XML tree now looks like:
<books>
    <book>
        <name>ABCD</name>
    </book>
    <book>
        <name>EFGH</name>
    </book>
</books>

From what documentation I have read on SimpleXMLElement, addChild() won't get this done for you as it doesn't support XML data as tag value.

Any ideas on how I should go about this ?

Thanks, m^e

+1  A: 

Two solutions. First, you do it yourself: you have to import your $sx object to DOM, create a DOMDocumentFragment and use appendXML().

Or, second solution: you grab SimpleDOM and you use insertXML(), which works like the addXMLChild() method you were describing.

include 'SimpleDOM.php';

$books = simpledom_load_string(
    '<books>
        <book>
            <name>ABCD</name>
        </book>
    </books>'
);

$books->insertXML(
    '<book>
        <name>EFGH</name>
    </book>'
);
Josh Davis
I'd go for the 1st method as it doesn't involve any external libraries. Played around with the code a bit and managed to figure out the exact code sequence. Thanks. That helped bigtime :)
miCRoSCoPiC_eaRthLinG
Please contribute with the exact code sequence if you still have it...!
maralbjo
A: 

Hi there. I have tried to get around this assumably simple issue of updating an XML file, but I struggle. Have a look at my code:

$doc = new DOMDocument();       
$doc->loadXML("<root/>");       

$fragment = $doc->createDocumentFragment();     
$fragment->appendXML("<foo>text</foo><bar>text2</bar>");
$doc->documentElement->appendChild($fragment);                      
echo $doc->saveXML(); 
$numberOfBytesWritten = file_put_contents("test.xml", $doc);
echo "We wrote " . $numberOfBytesWritten . " number of bytes.";

I have checked file permissions, and I would have expected the creation of an XML file on my server with this code. Alas, nothing is written.

Please point me in the right directions here!

maralbjo