Paulo Hgo
Paulo Hgo

Reputation: 860

Modify XML prolog in PHP

I'm reading an XML file with Simplexml and outputting a translated XML file with a different name. Google Translate outputs everything in UTF-8 and in order to properly view extended characters I need the XML Prolog to contain the encoding info:

<?xml version="1.0" encoding="UTF-8"?>

Some files have no encoding info or even no prolog at all. Is there a specific method to change or add prolog info in XML files through PHP? Thank you.

Upvotes: 1

Views: 716

Answers (1)

har07
har07

Reputation: 89315

For example, consider the following XML string with undesired XML declaration format. You can use DOMDocument to get only the XML content without declaration, like so :

$raw = '<?xml version="1.0"?><root/>';

$xml = new DOMDocument();
$xml->loadXML($raw);
$raw_without_prolog = $xml->saveXML($xml->documentElement);

From this point, you can simply prepend your standard XML declaration to produce the desired XML in whatever type (plain string, DOMDocument, SimpleXMLElement, either one should be as easy) :

.....
.....
$prolog = '<?xml version="1.0" encoding="UTF-8"?>';

$new_xml = new DOMDocument();
$new_xml->loadXML($prolog . $raw_without_prolog);

echo $new_xml->saveXML();

eval.in demo

Upvotes: 1

Related Questions