Search code examples
xmlcakephpencodingucs2

CakePHP set XML view encoding to UCS2


I need to set the encoding of my XML view to UCS2. I have tried to add the following to the view:

<?xml version="1.0" encoding="UCS-2"?>

and

<?php header('Content-type: text/xml; charset=UCS-2'); ?>

I have also tried to put this in the controller of the view:

$this->header('Content-type: text/xml; charset=UCS-2');

But each time when I open the xml view in the browser, save it to my desktop and open it with Notepad++ to check the file encoding it is set to UTF-8 without BOM.

I would really appreciate any suggestions on how to set the encoding for the specific XML view. TIA


Solution

  • The encoding is being read from the App.encoding configuration option, so what you could do is change it accordingly to UCS-2 in the specific action that generates the XML document.

    Additionally you'll probably also have to change the charset of the response, as it's initially being set in the CakeResponse constructor.

    public function xyzAction() {
        Configure::write('App.encoding', 'UCS-2');
        $this->response->charset('UCS-2');
    
        // ...
    
        $this->set('_serialize', /* ... */);
    
        // ...
    }
    

    This should not only change the encoding attribute in the XML document, but also the charset of the Content-Type header.