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.
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
The DOMDoc proposal of Cristian Toma seems a good approach if the document isn't too heavy. You could wrap it up in something like this:
Comes in useful when you don't have access to the serializer producing the xml.
Simple and clear only do this
OutPut
to add attributes in element only use
to add child use
If you don't specify an encoding, SimpleXML cannot (sanely) guess which one you intended.
You can try this, but you must use simplexml_load_string for $xml
Or you can still use other means to add the encoding to your output.
Simple Replacement
Regular Expressions
DOMDocument - I know you said you don't want to use DOMDocument, but here is an example
You can wrap this code into a function that receives a parameter $encoding and adds it to the