2017-04-14 27 views
0

我遇到了我的共享主机提供商和我的128Mb内存限制问题。我将AJAX中的数据插入到一个PHP控制器中,该控制器获取一个文件,解析AJAX中的新数据并用原始内容+新数据覆盖该文件。我们正在处理一个JSON文件。PHP内存限制与激烈的json文件更新

在这一点上,主人已经把我所有的东西都绊倒了。 JSON的大小达到16Mb之前,废话击中风扇。如果我们有任何建议来更有效地整合数据,我将不胜感激。我现在将内存限制甩到-1 - 我很乐意避免这样做!

这里是我的代码

<?php 

function appendCurrentFile($payload) { 

$_POST['payload'] = null; // CLEAR post payload 

ini_set("memory_limit",-1); // Fixes the problem the WRONG WAY 

$files = glob('/path/*'); // Get all json files in storage directory 

natsort($files); // Files to array 

$lastFile = array_pop($files); // Get last file (most recent JSON dump) 

$fileData = json_decode(file_get_contents($lastFile)); // Load file contents into it's own array 

$payload = json_decode($payload); // Take the POST payload from AJAX and parse into array 

$newArray = array_merge($fileData->cards, $payload); // Merge the data from our file and our payload 

$payload = null; // Clear payload variable 

$fileData->cards = $newArray; // Set the file object array as our new, merged array 

$newArray = null; // Clear our merged array 

file_put_contents($lastFile, json_encode($fileData, JSON_UNESCAPED_SLASHES)); // Overwrite latest file with existing data + new data. 

echo 'JSON updated! Memory Used: '.round((memory_get_peak_usage()/134217728 * 100), 0).'%'; // Report how badly we're abusing our memory 

} 
?> 
+0

https://stackoverflow.com/questions/4049428/processing-large-json-files-in-php –

+0

你抓住的最后一个文件,新数据添加到它,写一个新的更大的文件,并重复广告恶心?也许你的问题不是内存分配。 –

+0

请详细说明。 –

回答

0

二手的fopen( 'file.json', 'A +'),以及一些字符串操作代替。减少内存负载。每次总计约1%,而不是每个轮询(从允许的最大内存)增加1-3%的内存使用量。编辑:感谢您的回应!

$files = glob('/path/*'); // Get all json files in storage directory 

natsort($files); // Files to array 

$lastFile = array_pop($files); // Get last file (most recent JSON dump) 

$file = fopen($lastFile, 'a+'); // Stream file with write access, put cursor at end 

fwrite($file, $payload); // Insert json chunk into end of file. 

fclose($file); // Close file 

echo 'JSON updated! Memory Used: '.round((memory_get_peak_usage()/134217728 * 100), 0).'%'; // Report how badly we're abusing our memory (Now only 1% of total memory each time instead of 1-3% incremented per poll.