-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathxml2Array.php
More file actions
58 lines (46 loc) · 1.72 KB
/
xml2Array.php
File metadata and controls
58 lines (46 loc) · 1.72 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
<?php
/* Taken from http://www.php.net/manual/en/function.xml-parse.php#52567
Modified by Martin Guppy <http://www.deadpan110.com/>
Usage
Grab some XML data, either from a file, URL, etc. however you want.
Assume storage in $strYourXML;
$arrOutput = new xml2Array($strYourXML);
print_r($arrOutput); //print it out, or do whatever!
*/
class xml2Array {
private $arrOutput = array();
private $resParser;
private $strXmlData;
public function xmlParse($strInputXML) {
$this->resParser = xml_parser_create();
xml_set_object($this->resParser, $this);
xml_set_element_handler($this->resParser, "tagOpen", "tagClosed");
xml_set_character_data_handler($this->resParser, "tagData");
$this->strXmlData = xml_parse($this->resParser, $strInputXML);
if (!$this->strXmlData) {
die(sprintf("XML error: %s at line %d", xml_error_string(xml_get_error_code($this->resParser)), xml_get_current_line_number($this->resParser)));
}
xml_parser_free($this->resParser);
// Changed by Deadpan110
//return $this->arrOutput;
return $this->arrOutput[0];
}
private function tagOpen($parser, $name, $attrs) {
$tag = array("name" => $name, "attrs" => $attrs);
array_push($this->arrOutput, $tag);
}
private function tagData($parser, $tagData) {
if (trim($tagData)) {
if (isset($this->arrOutput[count($this->arrOutput) - 1]['tagData'])) {
$this->arrOutput[count($this->arrOutput) - 1]['tagData'] .= $tagData;
} else {
$this->arrOutput[count($this->arrOutput) - 1]['tagData'] = $tagData;
}
}
}
private function tagClosed($parser, $name) {
$this->arrOutput[count($this->arrOutput) - 2]['children'][] = $this->arrOutput[count($this->arrOutput) - 1];
array_pop($this->arrOutput);
}
}
?>