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.