views:

1097

answers:

3

This:

$XML = new SimpleXMLElement("<foo />");
echo($XML->asXML());

...outputs this:

<?xml version="1.0"?>
<foo/>

But I want it to output the encoding, too:

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

Is there some way to tell SimpleXMLElement to include the encoding attribute of the <?xml?> tag? Aside from doing this:

$XML = new SimpleXMLElement("<?xml version='1.0' encoding='utf-8'?><foo />");
echo($XML->asXML());

Which works, but it's annoying to have to manually specify the version and encoding.

Assume for the purposes of this question that I cannot use DOMDocument instead.

A: 

I would say you will need to do this on creation of each XML object. Even if SimpleXMLElement had a way of setting it you would still need to set it as I guess it would be possible for the object to pick a valid default.

Maybe create a constant and Create objects like this

$XML = new SimpleXMLElement($XMLNamespace . "<foo />");
echo($XML->asXML());
Toby Allen
A: 

If you don't specify an encoding, SimpleXML cannot (sanely) guess which one you intended.

TML
I know, but the only way to specify an encoding for SimpleXML is to make it explicit in the constructor -- and then you have to specify the XML version attribute too, or it throws an error. I can obviously do it that way, it's just annoying to have to do it at all.I guess SimpleXML is a little too simple :)
dirtside
+2  A: 

You can try this, but you must use simplexml_load_string for $xml

$xml // Your main SimpleXMLElement
$xml->addAttribute('encoding', 'UTF-8');

Or you can still use other means to add the encoding to your output.

Simple Replacement

$outputXML=str_replace('<?xml version="1.0"?>', '<?xml version="1.0" encoding="UTF-8"?>', $outputXML);

Regular Expressions

$outputXML=preg_replace('/<\?\s*xml([^\s]*)\?>/' '<?xml $1 encoding="UTF-8"?>', $outputXML);

DOMDocument - I know you said you don't want to use DOMDocument, but here is an example

$xml=dom_import_simplexml($simpleXML);
$xml->xmlEndoding='UTF-8';
$outputXML=$xml->saveXML();

You can wrap this code into a function that receives a parameter $encoding and adds it to the

Christian Toma