From 01962f039bde9eea87b04de5a768be448f2a8bd0 Mon Sep 17 00:00:00 2001 From: carcabot Date: Fri, 11 Jul 2014 15:08:58 +0300 Subject: [PATCH] Added XML Support --- RestServer.php | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/RestServer.php b/RestServer.php index a3fe561..de43b4f 100755 --- a/RestServer.php +++ b/RestServer.php @@ -33,12 +33,14 @@ class RestFormat const HTML = 'text/html'; const AMF = 'applicaton/x-amf'; const JSON = 'application/json'; + const XML = 'application/xml'; static public $formats = array( 'plain' => RestFormat::PLAIN, 'txt' => RestFormat::PLAIN, 'html' => RestFormat::HTML, 'amf' => RestFormat::AMF, 'json' => RestFormat::JSON, + 'xml' => RestFormat::XML, ); } @@ -405,6 +407,20 @@ public function sendData($data) $serializer = new Zend_Amf_Parse_Amf3_Serializer($stream); $serializer->writeTypeMarker($data); $data = $stream->getStream(); + + elseif ($this->format == RestFormat::XML) { + + if (is_object($data) && method_exists($data, '__keepOut')) { + $data = clone $data; + foreach ($data->__keepOut() as $prop) { + unset($data->$prop); + } + } + $data = $this->xml_encode($data); + if ($data && $this->mode == 'debug') { + $data = $this->json_format($data); + } + } else { if (is_object($data) && method_exists($data, '__keepOut')) { $data = clone $data; @@ -427,6 +443,44 @@ public function setStatus($code) header("{$_SERVER['SERVER_PROTOCOL']} $code"); } + private function xml_encode($mixed, $domElement=null, $DOMDocument=null) { + if (is_null($DOMDocument)) { + $DOMDocument =new DOMDocument; + $DOMDocument->formatOutput = true; + $this->xml_encode($mixed, $DOMDocument, $DOMDocument); + echo $DOMDocument->saveXML(); + } + else { + if (is_array($mixed)) { + foreach ($mixed as $index => $mixedElement) { + if (is_int($index)) { + if ($index === 0) { + $node = $domElement; + } + else { + $node = $DOMDocument->createElement($domElement->tagName); + $domElement->parentNode->appendChild($node); + } + } + else { + $plural = $DOMDocument->createElement($index); + $domElement->appendChild($plural); + $node = $plural; + if (!(rtrim($index, 's') === $index)) { + $singular = $DOMDocument->createElement(rtrim($index, 's')); + $plural->appendChild($singular); + $node = $singular; + } + } + + $this->xml_encode($mixedElement, $node, $DOMDocument); + } + } + else { + $domElement->appendChild($DOMDocument->createTextNode($mixed)); + } + } +} // Pretty print some JSON private function json_format($json) {