0
$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>";
2
  • 1
    This is not an "xml string." This is a string alright, but this is not XML. A XML document has exactly one single root element. Commented Feb 19, 2010 at 13:57
  • 1
    The correct term is well-formed. It's not a well-formed XML document. Commented Feb 19, 2010 at 14:10

4 Answers 4

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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.

Comments

0

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>';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.