Getting SimpleXMLElement to include the encoding in output

前端 未结 5 957
梦如初夏
梦如初夏 2020-12-09 10:26

This:

$XML = new SimpleXMLElement(\"\");
echo($XML->asXML());

...outputs this:



        
相关标签:
5条回答
  • 2020-12-09 10:46

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

    0 讨论(0)
  • 2020-12-09 11:04

    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

    0 讨论(0)
  • 2020-12-09 11:04

    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.

    0 讨论(0)
  • 2020-12-09 11:05

    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());
    
    0 讨论(0)
  • 2020-12-09 11:06

    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');
    
    0 讨论(0)
提交回复
热议问题