-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathpackxml.php
More file actions
66 lines (59 loc) · 1.47 KB
/
packxml.php
File metadata and controls
66 lines (59 loc) · 1.47 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
<?php
/**
* Minify XML source
*
* @package Packer
* @author Vallo Reima
* @copyright (C)2015
*/
class PackXML {
private $input;
private $nodes = []; /* node objects to remove */
/**
* @param string $source
* @param array $options
* @return mixed -- string - ok
*/
public static function minify($source, $options = []) {
$min = new self($source);
return $min->process();
}
/**
* @param string $input
*/
public function __construct($input) {
$this->input = $input;
}
/**
* minify
* @return string|false
*/
private function process() {
$dom = new DOMDocument();
$dom->preserveWhiteSpace = false;
$dom->formatOutput = false;
if (@$dom->loadXML($this->input)) {
$this->Detect($dom); // fix excessive nodes
foreach ($this->nodes as $node) {
$node->parentNode->removeChild($node); // remove fixed nodes
}
$rlt = $dom->saveXML(); // convert to string
} else { // bad content
$rlt = false;
}
return $rlt;
}
/**
* collect excessive node objects
* @param object $root
*/
private function Detect($root) {
foreach ($root->childNodes as $node) {
if ($node->nodeType == XML_COMMENT_NODE || ($node->nodeType == XML_TEXT_NODE && trim($node->nodeValue) == '')) {
array_push($this->nodes, $node); // comment or empty text
} else if ($node->nodeType == XML_ELEMENT_NODE) {
$this->Detect($node); // recurse subnodes
}
}
}
}