forked from codeigniter4/CodeIgniter4
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathXMLFormatter.php
More file actions
65 lines (57 loc) · 1.79 KB
/
Copy pathXMLFormatter.php
File metadata and controls
65 lines (57 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<?php namespace CodeIgniter\API;
class XMLFormatter implements FormatterInterface
{
/**
* Takes the given data and formats it.
*
* @param $data
*
* @return mixed
*/
public function format(array $data)
{
$result = null;
// SimpleXML is installed but default
// but best to check, and then provide a fallback.
if (! extension_loaded('simplexml'))
{
throw new \RuntimeException('The SimpleXML extension is required to format XML.');
}
$output = new \SimpleXMLElement("<?xml version=\"1.0\"?><response></response>");
$this->arrayToXML($data, $output);
return $output->asXML();
}
//--------------------------------------------------------------------
/**
* A recursive method to convert an array into a valid XML string.
*
* Written by CodexWorld. Received permission by email on Nov 24, 2016 to use this code.
*
* @see http://www.codexworld.com/convert-array-to-xml-in-php/
*
* @param array $data
* @param $output
*/
protected function arrayToXML(array $data, &$output)
{
foreach ($data as $key => $value)
{
if (is_array($value))
{
if (! is_numeric($key))
{
$subnode = $output->addChild("$key");
$this->arrayToXML($value, $subnode);
} else
{
$subnode = $output->addChild("item{$key}");
$this->arrayToXML($value, $subnode);
}
} else
{
$output->addChild("$key", htmlspecialchars("$value"));
}
}
}
//--------------------------------------------------------------------
}