forked from salsify/jsonstreamingparser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample.php
More file actions
83 lines (68 loc) · 1.8 KB
/
example.php
File metadata and controls
83 lines (68 loc) · 1.8 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
83
<?php
require_once dirname(__FILE__).'/../src/JsonStreamingParser/Listener.php';
require_once dirname(__FILE__).'/../src/JsonStreamingParser/Parser.php';
/**
* This basic implementation of a listener simply constructs an in-memory
* representation of the JSON document, which is a little silly since the whole
* point of a streaming parser is to avoid doing just that. However, it gets
* the point across.
*/
class ArrayMaker implements \JsonStreamingParser\Listener {
private $_json;
private $_stack;
private $_key;
public function get_json() {
return $this->_json;
}
public function start_document() {
$this->_stack = array();
$this->_key = null;
}
public function end_document() {
// w00t!
}
public function start_object() {
array_push($this->_stack, array());
}
public function end_object() {
$obj = array_pop($this->_stack);
if (empty($this->_stack)) {
// doc is DONE!
$this->_json = $obj;
} else {
$this->value($obj);
}
}
public function start_array() {
$this->start_object();
}
public function end_array() {
$this->end_object();
}
// Key will always be a string
public function key($key) {
$this->_key = $key;
}
// Note that value may be a string, integer, boolean, null
public function value($value) {
$obj = array_pop($this->_stack);
if ($this->_key) {
$obj[$this->_key] = $value;
$this->_key = null;
} else {
array_push($obj, $value);
}
array_push($this->_stack, $obj);
}
}
$testfile = dirname(__FILE__).'/example.json';
$listener = new ArrayMaker();
$stream = fopen($testfile, 'r');
try {
$parser = new \JsonStreamingParser\Parser($stream, $listener);
$parser->parse();
} catch (Exception $e) {
fclose($stream);
throw $e;
}
var_dump($listener->get_json());