Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

simplexml adding 'encoding' attribute to xml declaration

33 views
Skip to first unread message

Basewind

unread,
Feb 24, 2012, 10:17:48 PM2/24/12
to
I'm creating an xml file using simplexml, but would like to add the encoding="UTF-8" to the XML declaration. Like this:

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

How can I do this?

Here's my code:

<?php
$namesXML = new SimpleXMLElement("<names></names>");
echo $namesXML->asXML();

This shows:

<?xml version="1.0" ?><!-- want the encoding attribute added here -->
<names/>

Thanks!

Thomas 'PointedEars' Lahn

unread,
Feb 25, 2012, 2:40:33 PM2/25/12
to
It is called *Simple*XML*Element* for a reason. However, this particular
character encoding declaration is superfluous; UTF-8 is one of the XML
default encodings [1].

And do use header() to declare the XML media type that fits your data best.
Keep in mind that PHP's default is text/html which is not appropriate for
that kind of output.


PointedEars
___________
[1] <http://www.w3.org/TR/REC-xml/#charencoding>
--
var bugRiddenCrashPronePieceOfJunk = (
navigator.userAgent.indexOf('MSIE 5') != -1
&& navigator.userAgent.indexOf('Mac') != -1
) // Plone, register_function.js:16

"Álvaro G. Vicario"

unread,
Feb 27, 2012, 4:34:55 AM2/27/12
to
As far as I know, the only way is providing the full <?xml...?> tag in
the constructor:

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

SimpleXML will display the tag as-is (though it will not actually _use_
the encoding information). It'll use UTF-8 no matter what you type there.


--
-- http://alvaro.es - Álvaro G. Vicario - Burgos, Spain
-- Mi sitio sobre programación web: http://borrame.com
-- Mi web de humor satinado: http://www.demogracia.com
--
0 new messages