views:

121

answers:

4
$contents  = "<?xml version='1.0' ?>
        <authed>1</authed>
            <book>read</book>";

im having a xml string like this i want to add all the elements inside root tag

like this

$contents  = "<?xml version='1.0' ?>
        <root>
        <authed>1</authed>
            <book>read</book>
        </root>";
+1  A: 

String operations on XML are just like regex operations on HTML. This answer puts it in perspective.

SF.
A: 

You could use substr to extract the first part (xml version) and the second part (the elements) and then recombine

Dominik
A: 

If adding the root element is the only thing you want to do, you could do

$contents = str_replace("<?xml version='1.0' ?>", 
                        "<?xml version='1.0' ?><root>", 
                        $contents . '</root>');

This would replace the prolog with itself plus the root element inside the content and appended closing root tag. However, keep in mind that technically, we are just inserting random strings here, not nodes, which means <root> is handled the same as oot><aut. The angle brackets have no special meaning when working with strings. We defined the semantics ourselves. This is okay for a simple usecase like above.

But if you want to work with nodes, consider using one the XML libraries of PHP.

Gordon
A: 

This is not valid XML. A XML document has exactly one single root element. Whatever generated that not-XML tag soup should be fixed so that it outputs some valid XML.

Otherwise, if you're asking for trouble you can use any kind of string replacement.

$contents = preg_replace('#^<\\?.*?\\?>#', '$0<root>', $contents) . '</root>';
Josh Davis