Files
kiri-core/http-server/Http/Formatter/XmlFormatter.php
T
2020-08-31 12:38:32 +08:00

88 lines
1.4 KiB
PHP

<?php
/**
* Created by PhpStorm.
* User: whwyy
* Date: 2018/4/8 0008
* Time: 17:29
*/
namespace HttpServer\Http\Formatter;
use HttpServer\Application;
use SimpleXMLElement;
use Swoole\Http\Response;
use HttpServer\IInterface\IFormatter;
/**
* Class XmlFormatter
* @package Snowflake\Snowflake\Http\Formatter
*/
class XmlFormatter extends Application implements IFormatter
{
public $data = '';
/** @var Response */
public $status;
public $header = [];
/**
* @param $data
* @return $this
* @throws \Exception
*/
public function send($data)
{
if (!is_string($data)) {
// TODO: Implement send() method.
$dom = new SimpleXMLElement('<xml/>');
$this->toXml($dom, $data);
$this->data = $dom->saveXML();
}
return $this;
}
/**
* @return string
*/
public function getData()
{
$data = $this->data;
$this->clear();
return $data;
}
/**
* @param SimpleXMLElement $dom
* @param $data
*/
public function toXml($dom, $data)
{
foreach ($data as $key => $val) {
if (is_numeric($key)) {
$key = 'item' . $key;
}
if (is_array($val)) {
$node = $dom->addChild($key);
$this->toXml($node, $val);
} else if (is_object($val)) {
$val = get_object_vars($val);
$node = $dom->addChild($key);
$this->toXml($node, $val);
} else {
$dom->addChild($key, htmlspecialchars($val));
}
}
}
public function clear()
{
unset($this->data);
}
}