首页 > 解决方案 > 降低 PHP 脚本的内存使用量?

问题描述

因此,我从 API 端点获取数据并将其添加到我已经拥有的 CSV 文件的末尾,然后重新编写 CSV(这是必需的,因为稍后我需要为我从中提取的每个端点提供日志) .

我是 PHP 新手,不太确定降低内存使用率的最佳方法。我环顾四周,但对我来说没有什么特别突出的。

在下面的具体示例中,CSV 文件中有大约 100,000 行。

按照运行脚本时的 memory_get_usage 顺序,我得到了 58982400、103546880、103546880。我想降低使用的内存。在尝试降低使用的内存时,是否有任何提示或事项需要我注意?看起来有 1/2 的内存被用于从端点获取数据,我认为对于这种使用我无能为力?

来自 CSV 的数据基本上是

PersonId,FirstName,LastName,Gender

虽然来自端点的数据是

PersonId,EmailAddress

这是我的脚本。

<?php
include('ApiClient.include.php');
$urlStudents = "http://localhost/jsonyes.json";
$crl = curl_init();
curl_setopt($crl, CURLOPT_URL, $urlStudents);
curl_setopt($crl, CURLOPT_RETURNTRANSFER, 1);
$execCrl = curl_exec($crl);
$emails = json_decode($execCrl, true);
curl_close($crl);
$fp = fopen('turkeytest.csv', 'r');
$output = fopen("$emailFile", 'w');
$max = 0;
echo "Using GetUse ", memory_get_usage(True), " bytes of ram.";

foreach($emails as $email){
    if(!isset($eData[$email['PersonId']])){
        $eData[$email['PersonId']][] = $email['EmailAddress'];
    } else{
        $eData[$email['PersonId']][] = $email['EmailAddress'];
    }
    if(count($eData[$email['PersonId']]) > $max){
        $max = count($eData[$email['PersonId']]);
    }
} 
echo "Using GetUse ", memory_get_usage(True), " bytes of ram.";

while($row = fgetcsv($fp, ",")){
    $count = count($row);
    if(isset($eData[$row[0]])){
        foreach($eData[$row[0]] as $key => $value){
            $row[] = $value;
        }
    }
    $row = array_pad($row, $max+$count, '');
    fputcsv($output, $row); //writes array $datas to $output file
}
fclose($fp);
echo "Using GetUse ", memory_get_usage(True), " bytes of ram.";
?>

标签: php

解决方案


推荐阅读