Rectangle 27 1

I dont want xml writer to encode the multilingual characters , how this is possible ?

Actually as you write XML you already encode. What you mean is that you don't want to use numeric entities for these two characters which is possible but not always.

To not use numeric entities, you need to match the encoding of the document with the encoding of your string. From the output you provided I can only guess a bit, those two characters probably stand for:

Which could mean (I do not speak any Chinese so far) something like Chinese Word.

XMLWriter in PHP will always put characters into a numeric entity (like and in your example) whenever the encoding of the document is not able to represent that character within the document.

If you are able to match both encodings XMLWriter will automatically not use the numeric entities.

US-ASCII

                                                                                                                                                                                                                                                                                                
<?php
$xmlWriter = new XMLWriter();
$xmlWriter->openMemory();
$xmlWriter->startDocument('1.0', 'US-ASCII');
$xmlWriter->startElement('root');
$xmlWriter->writeAttribute('value', 'pfel');
$xmlWriter->endDocument();
echo $xmlWriter->flush();
<?xml version="1.0" encoding="US-ASCII"?>
<root value="&#196;pfel"/>

is the numeric entity for the unicode character U+00C4 and if you look closely, C4 is the hexadecimal representation of decimal 196 which also shows that the numeric XML entity always represents the Unicode character number.

So the XML output uses the US-ASCII encoding which is not able to represent the from the UTF-8 encoded string in the PHP code and therefore properly encodes it with it's numeric entity to preserve the character information.

Now changing the encoding from:

to the UTF-8 encoding of the PHP string:

This would equally work with your example however, one important information in your question is missing: In which encoding is the string from that record?

If it is UTF-8 already, then like I outlined in the example above, it would work already:

<?php
$recordUTf8 = "... contents=\"Just <span style=\"color:red\">testing</span>:"
             ."\xE6\xBC\xA2\xE5\xAD\x97\"";
$encoding   = 'UTF-8';
$encoding   = 'US-ASCII';

$xmlWriter = new XMLWriter();
$xmlWriter->openMemory();
$xmlWriter->startDocument('1.0', $encoding);
$xmlWriter->startElement('record');
$xmlWriter->writeAttribute('value', $recordUTf8);
$xmlWriter->endDocument();
echo $xmlWriter->flush();

As this output show, no numeric entities are used here, however, the string is clearly UTF-8 encoded (in a binary safe manner here in case you use a different encoding for the PHP file if you copy it over).

So just to summarize at this point: The XML encoding need to match the encoding of the string to represent all characters not in numeric entities (apart from the ones used to encode XML itself like <, >, ', " and &).

These are pretty much XML basics. If the document has an encoding the character data can not be represented in but as XML supports Unicode, the fallback are numeric entities. You are trying to prevent this fallback by aligning the document encoding with the string encoding.

  • Obtain or re-encode the record from the database to UTF-8.
XMLWriter

I give these suggestions because UTF-8 is the default encoding of XML and UTF-8 support is quite well in PHP. Also XMLWriter expects Unicode strings to be UTF-8 encoded, there is no setting or option that allows you to change that, so the input already needs to be UTF-8 encoded.

However independent to the input string, you can naturally tell XMLWriter to use a different output encoding. For example any other Chinese or Unicode Encoding might be suitable for you and it is possible for XMLWriter output as long as your PHP configuration supports that specific output encoding (check the iconv library you have).

When you start the document with XMLWriter, the second parameter specifies the encoding:

You can put in any encoding from the set of the encodings XML supports in the corresponding XML-Declaration:

<?xml version="1.0" encoding="ISO-8859-1"?><!-- Latin-1 example -->

In an encoding declaration, the values " UTF-8 ", " UTF-16 ", " ISO-10646-UCS-2 ", and " ISO-10646-UCS-4 " should be used for the various encodings and transformations of Unicode / ISO/IEC 10646, the values " ISO-8859-1 ", " ISO-8859-2 ", ... " ISO-8859- n " (where n is the part number) should be used for the parts of ISO 8859, and the values " ISO-2022-JP ", " Shift_JIS ", and " EUC-JP " should be used for the various encoded forms of JIS X-0208-1997. It is recommended that character encodings registered (as charsets) with the Internet Assigned Numbers Authority [IANA-CHARSETS], other than those just listed, be referred to using their registered names; other encodings should use names starting with an "x-" prefix. XML processors should match character encoding names in a case-insensitive way and should either interpret an IANA-registered name as the encoding registered at IANA for that name or treat it as unknown (processors are, of course, not required to support all IANA-registered encodings).

These specs are perhaps a little bit verbose. In the context of your question, all you need to do is to find out the encoding of your record-string. I btw. can't say I was not able to reproduce your exact output, I always get decimal entities, not hexa-decimal ones. You might be able to provide more information with a hex-dump of the string.

$xmlWriter->startDocument('1.0', $encoding);

php XML export issue with XMLWriter using writeAttribute() method - St...

php xml utf-8 character-encoding xmlwriter
Rectangle 27 2

/**
 * Build A XML Data Set
 *
 * @param array $data Associative Array containing values to be parsed into an XML Data Set(s)
 * @param string $startElement Root Opening Tag, default fx_request
 * @param string $xml_version XML Version, default 1.0
 * @param string $xml_encoding XML Encoding, default UTF-8
 * @return string XML String containig values
 * @return mixed Boolean false on failure, string XML result on success
 */
public static function arrayToXML($data, $startElement = 'fx_request', $xml_version = '1.0', $xml_encoding = 'UTF-8'){
    if(!is_array($data)){
        $err = 'Invalid variable type supplied, expected array not found on line '.__LINE__." in Class: ".__CLASS__." Method: ".__METHOD__;
        trigger_error($err);
        if($this->_debug) echo $err;
        return false; //return false error occurred
    }
    $xml = new XmlWriter();
    $xml->openMemory();
    $xml->startDocument($xml_version, $xml_encoding);
    $xml->startElement($startElement);

    /**
     * Write XML as per Associative Array
     * @param object $xml XMLWriter Object
     * @param array $data Associative Data Array
     */
    function write(XMLWriter $xml, $data){
        foreach($data as $key => $value){
            if (is_array($value) && isset($value[0])){
                foreach($value as $itemValue){
                    //$xml->writeElement($key, $itemValue);

                    if(is_array($itemValue)){
                        $xml->startElement($key);
                        write($xml, $itemValue);
                        $xml->endElement();
                        continue;
                    } 

                    if (!is_array($itemValue)){
                        $xml->writeElement($key, $itemValue."");
                    }
                }
            }else if(is_array($value)){
                $xml->startElement($key);
                write($xml, $value);
                $xml->endElement();
                continue;
            } 

            if (!is_array($value)){
                $xml->writeElement($key, $value."");
            }
        }
    }
    write($xml, $data);

    $xml->endElement();//write end element
    //returns the XML results
    return $xml->outputMemory(true);
}
$mArray["invitations"]["user"][0]["name"] = "paco";
$mArray["invitations"]["user"][0]["amigos"][0] = 82;
$mArray["invitations"]["user"][0]["amigos"][1] = 29;
$mArray["invitations"]["user"][0]["amigos"][2] = 6;

$mArray["invitations"]["user"][1]["name"] = "jose";
$mArray["invitations"]["user"][1]["amigos"][0] = 43;
$mArray["invitations"]["user"][1]["amigos"][1]["tuyos"] = 32;
$mArray["invitations"]["user"][1]["amigos"][1]["mios"] = 79;
$mArray["invitations"]["user"][1]["amigos"][2] = 11;

$mArray["invitations"]["user"][2]["name"] = "luis";
$mArray["invitations"]["user"][2]["amigos"][0] = 65;
<invitations>
<user>
    <name>paco</name>
    <amigos>82</amigos>
    <amigos>29</amigos>
    <amigos>6</amigos>
</user>
<user>
    <name>jose</name>
    <amigos>43</amigos>
    <amigos>
        <tuyos>32</tuyos>
        <mios>79</mios>
    </amigos>
    <amigos>11</amigos>
</user>
<user>
    <name>luis</name>
    <amigos>65</amigos>
</user>

I hope I can help someone with this

Passing PHP associative arrays to and from XML - Stack Overflow

php xml xml-serialization
Rectangle 27 2

/**
 * Build A XML Data Set
 *
 * @param array $data Associative Array containing values to be parsed into an XML Data Set(s)
 * @param string $startElement Root Opening Tag, default fx_request
 * @param string $xml_version XML Version, default 1.0
 * @param string $xml_encoding XML Encoding, default UTF-8
 * @return string XML String containig values
 * @return mixed Boolean false on failure, string XML result on success
 */
public static function arrayToXML($data, $startElement = 'fx_request', $xml_version = '1.0', $xml_encoding = 'UTF-8'){
    if(!is_array($data)){
        $err = 'Invalid variable type supplied, expected array not found on line '.__LINE__." in Class: ".__CLASS__." Method: ".__METHOD__;
        trigger_error($err);
        if($this->_debug) echo $err;
        return false; //return false error occurred
    }
    $xml = new XmlWriter();
    $xml->openMemory();
    $xml->startDocument($xml_version, $xml_encoding);
    $xml->startElement($startElement);

    /**
     * Write XML as per Associative Array
     * @param object $xml XMLWriter Object
     * @param array $data Associative Data Array
     */
    function write(XMLWriter $xml, $data){
        foreach($data as $key => $value){
            if (is_array($value) && isset($value[0])){
                foreach($value as $itemValue){
                    //$xml->writeElement($key, $itemValue);

                    if(is_array($itemValue)){
                        $xml->startElement($key);
                        write($xml, $itemValue);
                        $xml->endElement();
                        continue;
                    } 

                    if (!is_array($itemValue)){
                        $xml->writeElement($key, $itemValue."");
                    }
                }
            }else if(is_array($value)){
                $xml->startElement($key);
                write($xml, $value);
                $xml->endElement();
                continue;
            } 

            if (!is_array($value)){
                $xml->writeElement($key, $value."");
            }
        }
    }
    write($xml, $data);

    $xml->endElement();//write end element
    //returns the XML results
    return $xml->outputMemory(true);
}
$mArray["invitations"]["user"][0]["name"] = "paco";
$mArray["invitations"]["user"][0]["amigos"][0] = 82;
$mArray["invitations"]["user"][0]["amigos"][1] = 29;
$mArray["invitations"]["user"][0]["amigos"][2] = 6;

$mArray["invitations"]["user"][1]["name"] = "jose";
$mArray["invitations"]["user"][1]["amigos"][0] = 43;
$mArray["invitations"]["user"][1]["amigos"][1]["tuyos"] = 32;
$mArray["invitations"]["user"][1]["amigos"][1]["mios"] = 79;
$mArray["invitations"]["user"][1]["amigos"][2] = 11;

$mArray["invitations"]["user"][2]["name"] = "luis";
$mArray["invitations"]["user"][2]["amigos"][0] = 65;
<invitations>
<user>
    <name>paco</name>
    <amigos>82</amigos>
    <amigos>29</amigos>
    <amigos>6</amigos>
</user>
<user>
    <name>jose</name>
    <amigos>43</amigos>
    <amigos>
        <tuyos>32</tuyos>
        <mios>79</mios>
    </amigos>
    <amigos>11</amigos>
</user>
<user>
    <name>luis</name>
    <amigos>65</amigos>
</user>

I hope I can help someone with this

Passing PHP associative arrays to and from XML - Stack Overflow

php xml xml-serialization
Rectangle 27 0

If you would like to correct the CRLF that gets transformed to LF for text nodes after you call the Save method on the XmlDocument you can use a XmlWriterSettings instance. Uses the same XmlWriter as MilesDavies192s answer but also changes encoding to utf-8 and keeps indentation.

$xml = [xml]([System.IO.File]::ReadAllText($fileName))
$xml.PreserveWhitespace = $true

# Change some element

#Settings object will instruct how the xml elements are written to the file
$settings = New-Object System.Xml.XmlWriterSettings
$settings.Indent = $true
#NewLineChars will affect all newlines
$settings.NewLineChars ="`r`n"
#Set an optional encoding, UTF-8 is the most used (without BOM)
$settings.Encoding = New-Object System.Text.UTF8Encoding( $false )

$w = [System.Xml.XmlWriter]::Create($fileName, $settings)
try{
    $xml.Save( $w )
} finally{
    $w.Dispose()
}

Powershell saving XML and preserving format - Stack Overflow

powershell