123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151 |
- <?php
- namespace AlibabaCloud\Tea\XML;
- use XmlWriter;
- class ArrayToXml
- {
- private $version;
- private $encoding;
-
- public function __construct($xmlVersion = '1.0', $xmlEncoding = 'utf-8')
- {
- $this->version = $xmlVersion;
- $this->encoding = $xmlEncoding;
- }
-
- public function buildXML($data, $startElement = 'data')
- {
- if (!\is_array($data)) {
- $err = 'Invalid variable type supplied, expected array not found on line ' . __LINE__ . ' in Class: ' . __CLASS__ . ' Method: ' . __METHOD__;
- trigger_error($err);
- return false;
- }
- $xml = new XmlWriter();
- $xml->openMemory();
- $xml->startDocument($this->version, $this->encoding);
- $xml->startElement($startElement);
- $data = $this->writeAttr($xml, $data);
- $this->writeEl($xml, $data);
- $xml->endElement();
-
- return $xml->outputMemory(true);
- }
-
- protected function writeAttr(XMLWriter $xml, $data)
- {
- if (\is_array($data)) {
- $nonAttributes = [];
- foreach ($data as $key => $val) {
-
- if ('@' == $key[0]) {
- $xml->writeAttribute(substr($key, 1), $val);
- } elseif ('%' == $key[0]) {
- if (\is_array($val)) {
- $nonAttributes = $val;
- } else {
- $xml->text($val);
- }
- } elseif ('#' == $key[0]) {
- if (\is_array($val)) {
- $nonAttributes = $val;
- } else {
- $xml->startElement(substr($key, 1));
- $xml->writeCData($val);
- $xml->endElement();
- }
- } elseif ('!' == $key[0]) {
- if (\is_array($val)) {
- $nonAttributes = $val;
- } else {
- $xml->writeCData($val);
- }
- }
- else {
- $nonAttributes[$key] = $val;
- }
- }
- return $nonAttributes;
- }
- return $data;
- }
-
- protected function writeEl(XMLWriter $xml, $data)
- {
- foreach ($data as $key => $value) {
- if (\is_array($value) && !$this->isAssoc($value)) {
- foreach ($value as $itemValue) {
- if (\is_array($itemValue)) {
- $xml->startElement($key);
- $itemValue = $this->writeAttr($xml, $itemValue);
- $this->writeEl($xml, $itemValue);
- $xml->endElement();
- } else {
- $itemValue = $this->writeAttr($xml, $itemValue);
- $xml->writeElement($key, "{$itemValue}");
- }
- }
- } elseif (\is_array($value)) {
- $xml->startElement($key);
- $value = $this->writeAttr($xml, $value);
- $this->writeEl($xml, $value);
- $xml->endElement();
- } else {
- $value = $this->writeAttr($xml, $value);
- $xml->writeElement($key, "{$value}");
- }
- }
- }
-
- protected function isAssoc($array)
- {
- return (bool) \count(array_filter(array_keys($array), 'is_string'));
- }
- }
|