-
Notifications
You must be signed in to change notification settings - Fork 0
/
easyxmlparser.php
66 lines (61 loc) · 1.98 KB
/
easyxmlparser.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
56
57
58
59
60
61
62
63
64
65
66
<?php
class EasyXMLParser {
protected $filePath;
protected $fileHandle;
protected $fileContents;
public function __construct(string $filePath)
{
$this->filePath = $filePath;
}
public function handle()
{
return $this
->openFile() // Open the file and create a handle
->getContents() // Use the file handle to open a stream and get all content
->convertToArray(); // Convert result contents into an array
}
/**
* Open XML file for processing
* @return $this
*/
protected function openFile()
{
try {
$this->fileHandle = fopen($this->filePath, 'rb');
} catch (Exception $e) {
if ($e->getMessage()) die("Error binding file to stream: ".$e->getMessage());
else die("Error binding file to stream");
}
return $this;
}
/**
* Get the contents of the current file stream
* @return $this
*/
protected function getContents()
{
try {
$this->fileContents = stream_get_contents($this->fileHandle);
} catch (Exception $e) {
if ($e->getMessage()) die("Error fetching file stream content: ".$e->getMessage());
else die("Error fetching file stream content.");
}
// At this point we're done with the stream, so we can close it out
fclose($this->fileHandle);
return $this;
}
/**
* Convert file stream contents into readable array
* @return array [VaultWare properties]
*/
protected function convertToArray()
{
try {
$vwProperties = simplexml_load_string($this->fileContents, 'SimpleXMLElement', LIBXML_NOCDATA | LIBXML_NOBLANKS);
} catch (Exception $e) {
if ($e->getMessage()) die("Error converting stream contents into XML: ".$e->getMessage());
else die("Error converting stream contents into XML.");
}
return $vwProperties;
}
}