-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdigicol_json_to_xml.php
More file actions
294 lines (217 loc) · 7.1 KB
/
digicol_json_to_xml.php
File metadata and controls
294 lines (217 loc) · 7.1 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
<?php
// Licensed under the PHP License
//
// This is experimental code, not well-documented...
// Use at your own risk!
//
// Tim Strehle <tim@digicol.de>
require_once('digicol_console_options.class.php');
class Digicol_Json_To_Xml
{
protected $exit_on_unknown_options = true;
public function getHelpText()
{
return <<<EOT
Convert JSON to XML.
Simple JSON to XML conversion. JSON property names not allowed as XML tag names
will be represented as <_tag name="property name">.
Set <file> to "-" to read multiple file names or a single JSON object from STDIN.
(This allows you to use digicol_json_to_xml.php in conjunction with "find".)
Usage: php digicol_json_to_xml.php [ OPTIONS ] <file> [<file> ...]
-h, --help Display this help message and exit.
Copyright 2013 by Digital Collections Verlagsgesellschaft mbH.
Report bugs to: <tim@digicol.de>
EOT;
}
public function main($script_filename, $argv)
{
$this->parseOptions($argv);
$this->determineAction();
$this->executeAction();
}
public function parseOptions($argv)
{
$getopt = new Digicol_Console_Options($this->getOptionDefinitions());
$this->options = $getopt->parse($argv, $this->exit_on_unknown_options);
if (is_string($this->options))
{
fwrite(STDERR, sprintf("Unknown option \"%s\". Try -h for more information.\n", $this->options));
exit(1);
}
}
protected function getOptionDefinitions()
{
return array
(
array( 'help, h' , 0 )
);
}
public function determineAction()
{
$this->action = '';
if (isset($this->options[ 'help' ]))
{
$this->action = 'help';
return;
}
if (count($this->options[ '_' ]) > 0)
$this->action = 'convert';
}
public function executeAction()
{
if ($this->action == '')
{
fwrite(STDERR, "Nothing to do. Try -h for more information.\n");
exit(1);
}
$method = 'executeAction_' . $this->action;
$this->$method();
}
protected function executeAction_help()
{
fwrite(STDOUT, $this->getHelpText());
}
protected function executeAction_convert()
{
// Read from STDIN?
if ($this->options[ '_' ][ 0 ] === '-')
{
$first = true;
$mode = 'filename';
$buffer = '';
while (! feof(STDIN))
{
$line = fgets(STDIN);
// Check input - if the first line doesn't look like XML, we're in filename mode
// XXX rather dumb check: look for "{" and test whether this is an existing file
if ($first)
{
if (strpos($line, '{') !== false)
$mode = 'buffer';
}
if ($mode === 'buffer')
{
$buffer .= $line;
}
elseif ($line != '')
{
$this->processFile($line, 'filename');
}
$first = false;
}
if ($mode === 'buffer')
{
if ($buffer !== '')
$this->processFile($buffer, 'buffer');
}
}
else
{
foreach ($this->options[ '_' ] as $filename)
$this->processFile($filename, 'filename');
}
}
protected function processFile($filename, $mode)
{
if ($mode == 'filename')
{
if (! file_exists($filename))
{
fwrite(STDERR, sprintf("File <%s> does not exist.\n", $filename));
return;
}
}
if ($mode == 'filename')
{
$ok = $this->convertToXml(file_get_contents($filename), $filename);
}
elseif ($mode == 'buffer')
{
$ok = $this->convertToXml($filename, 'stdin');
}
}
protected function convertToXml($buffer, $filename)
{
fwrite(STDOUT, '<?xml version="1.0" encoding="UTF-8"?>' . "\n");
fwrite(STDOUT, $this->jsonToXml('json', json_decode($buffer, true), 0));
return 1;
}
protected function jsonToXml($tag, $data, $level)
{
$result = '';
$this->makeTag($tag, $open_tag, $close_tag);
if (! is_array($data))
{
// Convert boolean values to 0/1
if ($data === true)
$data = '1';
if ($data === false)
$data = '0';
if (strlen($data) === 0)
return sprintf("%s<%s/>\n", str_repeat(' ', $level * 2), $open_tag);
$result .= sprintf
(
"%s<%s>%s</%s>\n",
str_repeat(' ', $level * 2),
$open_tag,
htmlspecialchars($data),
$close_tag
);
return $result;
}
$keys = array_keys($data);
// Empty array
if (count($keys) === 0)
return sprintf("%s<%s/>\n", str_repeat(' ', $level * 2), $open_tag);
// Dumb numeric array detection
if (is_numeric($keys[ 0 ]))
{
foreach ($keys as $key)
$result .= $this->jsonToXml($tag, $data[ $key ], $level);
}
else
{
$result .= sprintf("%s<%s>\n", str_repeat(' ', $level * 2), $open_tag);
foreach ($keys as $key)
$result .= $this->jsonToXml($key, $data[ $key ], $level + 1);
$result .= sprintf("%s</%s>\n", str_repeat(' ', $level * 2), $close_tag);
}
return $result;
}
protected function makeTag($tag, &$open_tag, &$close_tag)
{
$open_tag = $close_tag = $tag;
if (! $this->isValidTagName($tag))
{
$open_tag = sprintf('_tag name="%s"', htmlspecialchars($tag));
$close_tag = '_tag';
}
}
/**
* Check whether a string is a valid XML tag name
*
* Checks whether the given string is a valid XML tag name. The rules are basically:
* - no whitespace
* - no special characters, only A-Z, 0-9, ".", ":", "-" and "_"
* - must not begin with a number, ".", or "-"
* - must not begin with "xml"
*
* This validity check does not comply fully with the XML 1.0 specification in that it forbids umlauts
* although they should be allowed.
*
* @param string $tagname String to check
* @return bool True or false
*/
protected function isValidTagName($str)
{
if (! preg_match('/^[a-z_:]+[a-z0-9._:-]*$/i', $str))
return false;
if (strtolower(substr($str, 0, 3)) == 'xml')
return false;
return true;
}
}
// Execute
$script = new Digicol_Json_To_Xml();
$script->main(__FILE__, $argv);
?>