Getting SimpleXMLElement to include the encoding i

2019-01-17 22:03发布

问题:

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.

回答1:

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



回答2:

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');


回答3:

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());


回答4:

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.



回答5:

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