我正在使用一个从远程服务器调用文件的 API。该文件大约有 110,592 字节 (0.11 MB)。
但是,我有一个循环贯穿 $data
的每次迭代,并且它偶尔会返回以下错误:
PHP Fatal error: Out of memory (allocated 97255424) (tried to allocate 87 bytes)
我不知道为什么这偶尔会返回这个。我在另一个页面上有非常相似的代码,它通常可以解决零问题。
$json = file_get_contents('https://api.com/?limit=200');
$data = json_decode($json);
$x = 0;
while($x < sizeof($data)) {
$Id = $data[$x]->id;
$Name = $data[$x]->name; //ERROR LINE
$price = $data[$x]->price_usd;
$time = $data[$x]->last_updated; //SOMETIMES ERROR LINE
$sql = "INSERT INTO table (Id, name, price, time)
VALUES ('".$Id."', '".$Name."', '".$price."', '".$time."')";
if ($conn->query($sql) === TRUE) {
//echo "New record created successfully<br><br><br>";
} else {
die("Error: " . $sql . "<br>" . $conn->error."<br><br><br>");
}
$x = $x+1;
}
任何关于这方面的建议都会很棒。 (我还简化了代码,循环中变量多了,所有变量都进入了sql表)
编辑:我的 php 信息设置为:memory_limit 1024M
最佳答案
我不确定“api.com”(您正在交谈的 api)允许您做什么,但您应该能够减少每个循环必须处理的数据集。也许是这样的:
$pagesize = 100;
$pagenumber = 0;
while $data {
$data = file_get_contents('https://api.com/?limit='.$pagesize.'&limit-'.$pagenumber);
....do all the stuff
$pagenumber++;
}
关于PHP fatal error : Out of memory - Memory Allocation Strategies for Big Data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49288426/