summaryrefslogtreecommitdiff
path: root/framework/Xml/TXmlDocument.php
blob: 18f0611f980d0e4933bd49698850765819de64cd (plain)
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
<?php
/**
 * TXmlElement, TXmlDocument, TXmlElementList class file
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @link http://www.pradosoft.com/
 * @copyright Copyright &copy; 2005-2014 PradoSoft
 * @license http://www.pradosoft.com/license/
 * @package Prado\Xml
 */

namespace Prado\Xml;
use Prado\Exceptions\TIOException;

/**
 * TXmlDocument class.
 *
 * TXmlDocument represents a DOM representation of an XML file.
 * Besides all properties and methods inherited from {@link TXmlElement},
 * you can load an XML file or string by {@link loadFromFile} or {@link loadFromString}.
 * You can also get the version and encoding of the XML document by
 * the Version and Encoding properties.
 *
 * To construct an XML string, you may do the following:
 * <code>
 * $doc=new TXmlDocument('1.0','utf-8');
 * $doc->TagName='Root';
 *
 * $proc=new TXmlElement('Proc');
 * $proc->setAttribute('Name','xxxx');
 * $doc->Elements[]=$proc;
 *
 * $query=new TXmlElement('Query');
 * $query->setAttribute('ID','xxxx');
 * $proc->Elements[]=$query;
 *
 * $attr=new TXmlElement('Attr');
 * $attr->setAttribute('Name','aaa');
 * $attr->Value='1';
 * $query->Elements[]=$attr;
 *
 * $attr=new TXmlElement('Attr');
 * $attr->setAttribute('Name','bbb');
 * $attr->Value='1';
 * $query->Elements[]=$attr;
 * </code>
 * The above code represents the following XML string:
 * <code>
 * <?xml version="1.0" encoding="utf-8"?>
 * <Root>
 *   <Proc Name="xxxx">
 *     <Query ID="xxxx">
 *       <Attr Name="aaa">1</Attr>
 *       <Attr Name="bbb">1</Attr>
 *     </Query>
 *   </Proc>
 * </Root>
 * </code>
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @package Prado\Xml
 * @since 3.0
 */
class TXmlDocument extends TXmlElement
{
	/**
	 * @var string version of this XML document
	 */
	private $_version;
	/**
	 * @var string encoding of this XML document
	 */
	private $_encoding;

	/**
	 * Constructor.
	 * @param string version of this XML document
	 * @param string encoding of this XML document
	 */
	public function __construct($version='1.0',$encoding='')
	{
		parent::__construct('');
		$this->setVersion($version);
		$this->setEncoding($encoding);
	}

	/**
	 * @return string version of this XML document
	 */
	public function getVersion()
	{
		return $this->_version;
	}

	/**
	 * @param string version of this XML document
	 */
	public function setVersion($version)
	{
		$this->_version=$version;
	}

	/**
	 * @return string encoding of this XML document
	 */
	public function getEncoding()
	{
		return $this->_encoding;
	}

	/**
	 * @param string encoding of this XML document
	 */
	public function setEncoding($encoding)
	{
		$this->_encoding=$encoding;
	}

	/**
	 * Loads and parses an XML document.
	 * @param string the XML file path
	 * @return boolean whether the XML file is parsed successfully
	 * @throws TIOException if the file fails to be opened.
	 */
	public function loadFromFile($file)
	{
		if(($str=@file_get_contents($file))!==false)
			return $this->loadFromString($str);
		else
			throw new TIOException('xmldocument_file_read_failed',$file);
	}

	/**
	 * Loads and parses an XML string.
	 * The version and encoding will be determined based on the parsing result.
	 * @param string the XML string
	 * @return boolean whether the XML string is parsed successfully
	 */
	public function loadFromString($string)
	{
		// TODO: since PHP 5.1, we can get parsing errors and throw them as exception
		$doc=new \DOMDocument();
		if($doc->loadXML($string)===false)
			return false;

		$this->setEncoding($doc->encoding);
		$this->setVersion($doc->version);

		$element=$doc->documentElement;
		$this->setTagName($element->tagName);
		$this->setValue($element->nodeValue);
		$elements=$this->getElements();
		$attributes=$this->getAttributes();
		$elements->clear();
		$attributes->clear();

		static $bSimpleXml;
		if($bSimpleXml === null)
			$bSimpleXml = (boolean)function_exists('simplexml_load_string');

		if($bSimpleXml)
		{
			$simpleDoc = simplexml_load_string($string);
			$docNamespaces = $simpleDoc->getDocNamespaces(false);
			$simpleDoc = null;
			foreach($docNamespaces as $prefix => $uri)
			{
 				if($prefix === '')
   					$attributes->add('xmlns', $uri);
   				else
   					$attributes->add('xmlns:'.$prefix, $uri);
			}
		}

		foreach($element->attributes as $name=>$attr)
			$attributes->add(($attr->prefix === '' ? '' : $attr->prefix . ':') .$name,$attr->value);
		foreach($element->childNodes as $child)
		{
			if($child instanceof \DOMElement)
				$elements->add($this->buildElement($child));
		}

		return true;
	}

	/**
	 * Saves this XML document as an XML file.
	 * @param string the name of the file to be stored with XML output
	 * @throws TIOException if the file cannot be written
	 */
	public function saveToFile($file)
	{
		if(($fw=fopen($file,'w'))!==false)
		{
			fwrite($fw,$this->saveToString());
			fclose($fw);
		}
		else
			throw new TIOException('xmldocument_file_write_failed',$file);
	}

	/**
	 * Saves this XML document as an XML string
	 * @return string the XML string of this XML document
	 */
	public function saveToString()
	{
		$version=empty($this->_version)?' version="1.0"':' version="'.$this->_version.'"';
		$encoding=empty($this->_encoding)?'':' encoding="'.$this->_encoding.'"';
		return "<?xml{$version}{$encoding}?>\n".$this->toString(0);
	}

	/**
	 * Magic-method override. Called whenever this document is used as a string.
	 * <code>
	 * $document = new TXmlDocument();
	 * $document->TagName = 'root';
	 * echo $document;
	 * </code>
	 * or
	 * <code>
	 * $document = new TXmlDocument();
	 * $document->TagName = 'root';
	 * $xml = (string)$document;
	 * </code>
	 * @return string string representation of this document
	 */
	public function __toString()
	{
		return $this->saveToString();
	}

	/**
	 * Recursively converts DOM XML nodes into TXmlElement
	 * @param DOMXmlNode the node to be converted
	 * @return TXmlElement the converted TXmlElement
	 */
	protected function buildElement($node)
	{
		$element=new TXmlElement($node->tagName);
		$element->setValue($node->nodeValue);
		foreach($node->attributes as $name=>$attr)
			$element->getAttributes()->add(($attr->prefix === '' ? '' : $attr->prefix . ':') . $name,$attr->value);

		foreach($node->childNodes as $child)
		{
			if($child instanceof \DOMElement)
				$element->getElements()->add($this->buildElement($child));
		}
		return $element;
	}
}