Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting SimpleXMLElement to include the encoding in output

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.

like image 201
dirtside Avatar asked May 15 '09 16:05

dirtside


4 Answers

Simple and clear only do this

$XMLRoot = new SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?><element></element>');

OutPut

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

to add attributes in element only use

$XMLRoot->addAttribute('name','juan');

to add child use

$childElement = $XMLRoot->addChild('elementChild');
$childElement->addAttribute('attribName','somthing');
like image 38
DarckBlezzer Avatar answered Oct 23 '22 16:10

DarckBlezzer


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

like image 154
Cristian Toma Avatar answered Oct 23 '22 16:10

Cristian Toma


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:

private function changeEncoding(string $xml, string $encoding) {
    $dom = new \DOMDocument();
    $dom->loadXML($xml);
    $dom->encoding = $encoding;
    return $dom->saveXML();
}

Comes in useful when you don't have access to the serializer producing the xml.

like image 2
LevinM Avatar answered Oct 23 '22 17:10

LevinM


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());
like image 1
Toby Allen Avatar answered Oct 23 '22 15:10

Toby Allen