一種替代增加內存限制的PHP更大的價值是使用salsify/jsonstreamingparser
您需要創建自己的監聽器。
$testfile = '/path/to/file.json';
$listener = new MyListener();
$stream = fopen($testfile, 'r');
try {
$parser = new \JsonStreamingParser\Parser($stream, $listener);
$parser->parse();
fclose($stream);
} catch (Exception $e) {
fclose($stream);
throw $e;
}
爲了讓事情簡單地理解,我的「M使用此JSON例如:
JSON輸入
{
"objects": [
{
"propertyInt": 1,
"propertyString": "string",
"propertyObject": { "key": "value" }
},
{
"propertyInt": 2,
"propertyString": "string2",
"propertyObject": { "key": "value2" }
}]
}
你需要實現自己的聽衆在這種情況下,我只想得到陣列內的物體。
PHP
class MyListener extends \JsonStreamingParser\Listener\InMemoryListener
{
//control variable that allow us to know if is a child or parent object
protected $level = 0;
protected function startComplexValue($type)
{
//start complex value, increment our level
$this->level++;
parent::startComplexValue($type);
}
protected function endComplexValue()
{
//end complex value, decrement our level
$this->level--;
$obj = array_pop($this->stack);
// If the value stack is now empty, we're done parsing the document, so we can
// move the result into place so that getJson() can return it. Otherwise, we
// associate the value
if (empty($this->stack)) {
$this->result = $obj['value'];
} else {
if($obj['type'] == 'object') {
//insert value to top object, author listener way
$this->insertValue($obj['value']);
//HERE I call the custom function to do what I want
$this->insertObj($obj);
}
}
}
//custom function to do whatever
protected function insertObj($obj)
{
//parent object
if($this->level <= 2) {
echo "<pre>";
var_dump($obj);
echo "</pre>";
}
}
}
輸出
array(2) {
["type"]=>
string(6) "object"
["value"]=>
array(3) {
["propertyInt"]=>
int(1)
["propertyString"]=>
string(6) "string"
["propertyObject"]=>
array(1) {
["key"]=>
string(5) "value"
}
}
}
array(2) {
["type"]=>
string(6) "object"
["value"]=>
array(3) {
["propertyInt"]=>
int(2)
["propertyString"]=>
string(7) "string2"
["propertyObject"]=>
array(1) {
["key"]=>
string(6) "value2"
}
}
}
我測試了它反對與166MB一個JSON文件和它的作品。也許你需要讓聽衆適應你的需求。
你不應該爲你想要的使用循環。解析器只會發出你的回調應該處理的事件,並且做他們想要/需要處理的數據。或者有https://github.com/salsify/jsonstreamingparser。我不能擔保任何一個圖書館,所以你必須自己檢查一下。 – PeeHaa