class_xml.php
2.82 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
<?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: class_xml.php 27449 2012-02-01 05:32:35Z zhangguosheng $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
function xml2array(&$xml, $isnormal = FALSE) {
$xml_parser = new XMLparse($isnormal);
$data = $xml_parser->parse($xml);
$xml_parser->destruct();
return $data;
}
function array2xml($arr, $htmlon = TRUE, $isnormal = FALSE, $level = 1) {
$s = $level == 1 ? "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\r\n<root>\r\n" : '';
$space = str_repeat("\t", $level);
foreach($arr as $k => $v) {
if(!is_array($v)) {
$s .= $space."<item id=\"$k\">".($htmlon ? '<![CDATA[' : '').$v.($htmlon ? ']]>' : '')."</item>\r\n";
} else {
$s .= $space."<item id=\"$k\">\r\n".array2xml($v, $htmlon, $isnormal, $level + 1).$space."</item>\r\n";
}
}
$s = preg_replace("/([\x01-\x08\x0b-\x0c\x0e-\x1f])+/", ' ', $s);
return $level == 1 ? $s."</root>" : $s;
}
class XMLparse {
var $parser;
var $document;
var $stack;
var $data;
var $last_opened_tag;
var $isnormal;
var $attrs = array();
var $failed = FALSE;
function __construct($isnormal) {
$this->XMLparse($isnormal);
}
function XMLparse($isnormal) {
$this->isnormal = $isnormal;
$this->parser = xml_parser_create('ISO-8859-1');
xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, false);
xml_set_object($this->parser, $this);
xml_set_element_handler($this->parser, 'open','close');
xml_set_character_data_handler($this->parser, 'data');
}
function destruct() {
xml_parser_free($this->parser);
}
function parse(&$data) {
$this->document = array();
$this->stack = array();
return xml_parse($this->parser, $data, true) && !$this->failed ? $this->document : '';
}
function open(&$parser, $tag, $attributes) {
$this->data = '';
$this->failed = FALSE;
if(!$this->isnormal) {
if(isset($attributes['id']) && !is_string($this->document[$attributes['id']])) {
$this->document = &$this->document[$attributes['id']];
} else {
$this->failed = TRUE;
}
} else {
if(!isset($this->document[$tag]) || !is_string($this->document[$tag])) {
$this->document = &$this->document[$tag];
} else {
$this->failed = TRUE;
}
}
$this->stack[] = &$this->document;
$this->last_opened_tag = $tag;
$this->attrs = $attributes;
}
function data(&$parser, $data) {
if($this->last_opened_tag != NULL) {
$this->data .= $data;
}
}
function close(&$parser, $tag) {
if($this->last_opened_tag == $tag) {
$this->document = $this->data;
$this->last_opened_tag = NULL;
}
array_pop($this->stack);
if($this->stack) {
$this->document = &$this->stack[count($this->stack)-1];
}
}
}
?>