I’m just getting started in Yii and implementing the RESTful web services. I have it working well so far, but I to figure out how to customize the XML tags to meet a certain specification. Specifically, I need to change the XML tags, add namespaces, and add additional tags that are not in the original data.
I have the following MyXmlResponseFormatter coded as a subclass of XmlResponseFormatter, but I’m not what to do with it.
Where should I put it? And how do I register it as a custom response formatter? Do I do so in my config or in my controller files? I think I’m close, but I just can’t get it to work.
<?php
namespace app\subsplash;
use yii\web\XmlResponseFormatter;
class MyXmlResponseFormatter extends XmlResponseFormatter
{
/**
* @var string the name of the root element.
*/
public $rootTag = 'data';
/**
* @var string the name of the elements that represent the array elements with numeric keys.
*/
public $itemTag = 'row';
/**
* @var array of XML namespaces
*/
public $nameSpaces = [
'xmlns:foo' => 'h t t p : //example.com/foo', // (First post spaces added to avoid forbidden links)
'xmlns:bar' => 'h t t p : //example.com/bar',
];
/**
* @var string the title
*/
public $title = 'Untitled';
/**
* Formats the specified response.
* @param Response $response the response to be formatted.
*/
public function format($response)
{
$charset = $this->encoding === null ? $response->charset : $this->encoding;
if (stripos($this->contentType, 'charset') === false) {
$this->contentType .= '; charset=' . $charset;
}
$response->getHeaders()->set('Content-Type', $this->contentType);
$dom = new DOMDocument($this->version, $charset);
// Add root tag with namespaces
$root = new DOMElement($this->rootTag);
foreach ($this->nameSpaces as $ns => $url) {
$root->setAttributeNS($url, $ns);
}
$dom->appendChild($root);
// Add header with title
$header = new DOMElement('header');
$title = new DOMElement('title', $this->title);
$header->appendChild($title);
$dom->appendChild($header);
$this->buildXml($root, $response->data);
$response->content = $dom->saveXML();
}
}