forked from assimon/dujiaoka
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathXml.php
55 lines (54 loc) · 1.54 KB
/
Xml.php
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
<?php
namespace YS\app\libs;
class Xml
{
static $version = '1.0';
static $encoding = 'UTF-8';
/*** 将数据转为XML*/
public static function toXml($array)
{
$xml = '<xml>';
foreach ($array as $k => $v) {
$xml .= '<' . $k . '><![CDATA[' . $v . ']]></' . $k . '>';
}
$xml .= '</xml>';
return $xml;
}
public static function parseXml($xmlSrc)
{
if (empty($xmlSrc)) {
return false;
}
$array = array();
$xml = simplexml_load_string($xmlSrc);
$encode = Xml::getXmlEncode($xmlSrc);
if ($xml && $xml->children()) {
foreach ($xml->children() as $node) {
if ($node->children()) {
$k = $node->getName();
$nodeXml = $node->asXML();
$v = substr($nodeXml, strlen($k) + 2, strlen($nodeXml) - 2 * strlen($k) - 5);
} else {
$k = $node->getName();
$v = (string) $node;
}
if ($encode != "" && $encode != "UTF-8") {
$k = iconv("UTF-8", $encode, $k);
$v = iconv("UTF-8", $encode, $v);
}
$array[$k] = $v;
}
}
return $array;
}
static function getXmlEncode($xml)
{
$ret = preg_match("/<?xml[^>]* encoding=\"(.*)\" [^>]* ?>/i", $xml, $arr);
if ($ret) {
return strtoupper($arr[1]);
} else {
return "";
}
}
}
?>