XmlParser.php
2.46 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
<?php
/**
* Created by PhpStorm.
* User: Cibermag
* Date: 10.09.2015
* Time: 17:47
*/
namespace yii\multiparser;
class XmlParser implements ParserInterface{
public function read()
{
// TODO: Implement read() method.
}
public function setup()
{
// TODO: Implement setup() method.
}
/**
* Converts an XML string to a PHP array
* See http://phpsecurity.readthedocs.org/en/latest/Injection-Attacks.html#xml-external-entity-injection
*
* @uses recursiveXMLToArray()
* @param string $val
* @param boolean $disableDoctypes Disables the use of DOCTYPE, and will trigger an error if encountered.
* false by default.
* @param boolean $disableExternals Disables the loading of external entities. false by default.
* @return array
*/
public static function xml2array($val, $disableDoctypes = false, $disableExternals = false) {
// Check doctype
if($disableDoctypes && preg_match('/\<\!DOCTYPE.+]\>/', $val)) {
throw new InvalidArgumentException('XML Doctype parsing disabled');
}
// Disable external entity loading
if($disableExternals) $oldVal = libxml_disable_entity_loader($disableExternals);
try {
$xml = new SimpleXMLElement($val);
$result = self::recursiveXMLToArray($xml);
} catch(Exception $ex) {
if($disableExternals) libxml_disable_entity_loader($oldVal);
throw $ex;
}
if($disableExternals) libxml_disable_entity_loader($oldVal);
return $result;
}
/**
* Convert a XML string to a PHP array recursively. Do not
* call this function directly, Please use {@link Convert::xml2array()}
*
* @param SimpleXMLElement
*
* @return mixed
*/
protected static function recursiveXMLToArray($xml) {
if(is_object($xml) && get_class($xml) == 'SimpleXMLElement') {
$attributes = $xml->attributes();
foreach($attributes as $k => $v) {
if($v) $a[$k] = (string) $v;
}
$x = $xml;
$xml = get_object_vars($xml);
}
if(is_array($xml)) {
if(count($xml) == 0) return (string) $x; // for CDATA
foreach($xml as $key => $value) {
$r[$key] = self::recursiveXMLToArray($value);
}
if(isset($a)) $r['@'] = $a; // Attributes
return $r;
}
return (string) $xml;
}
}