123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102 |
- <?php
- namespace think\response;
- use think\Collection;
- use think\Model;
- use think\Response;
- class Xml extends Response
- {
-
- protected $options = [
-
- 'root_node' => 'think',
-
- 'root_attr' => '',
-
- 'item_node' => 'item',
-
- 'item_key' => 'id',
-
- 'encoding' => 'utf-8',
- ];
- protected $contentType = 'text/xml';
-
- protected function output($data)
- {
-
- return $this->xmlEncode($data, $this->options['root_node'], $this->options['item_node'], $this->options['root_attr'], $this->options['item_key'], $this->options['encoding']);
- }
-
- protected function xmlEncode($data, $root, $item, $attr, $id, $encoding)
- {
- if (is_array($attr)) {
- $array = [];
- foreach ($attr as $key => $value) {
- $array[] = "{$key}=\"{$value}\"";
- }
- $attr = implode(' ', $array);
- }
- $attr = trim($attr);
- $attr = empty($attr) ? '' : " {$attr}";
- $xml = "<?xml version=\"1.0\" encoding=\"{$encoding}\"?>";
- $xml .= "<{$root}{$attr}>";
- $xml .= $this->dataToXml($data, $item, $id);
- $xml .= "</{$root}>";
- return $xml;
- }
-
- protected function dataToXml($data, $item, $id)
- {
- $xml = $attr = '';
- if ($data instanceof Collection || $data instanceof Model) {
- $data = $data->toArray();
- }
- foreach ($data as $key => $val) {
- if (is_numeric($key)) {
- $id && $attr = " {$id}=\"{$key}\"";
- $key = $item;
- }
- $xml .= "<{$key}{$attr}>";
- $xml .= (is_array($val) || is_object($val)) ? $this->dataToXml($val, $item, $id) : $val;
- $xml .= "</{$key}>";
- }
- return $xml;
- }
- }
|