Search code examples
phpexcelpowershellshell-exec

PHP shell_exec System.OutOfMemoryException


I use the PowerShell module ImportExcel to convert Excel files to csv files:

exportCSV.ps1:

Param(
    [string]$cInput,
    [string]$cOutput,
    [string]$cSheet
)

if (!$cInput -Or !$cOutput -Or !$cSheet) { Write-Host "failed" }
else {
    try {
        Import-Excel -WorksheetName $cSheet -Path $cInput -NoHeader | Export-Csv $cOutput -NoTypeInformation -encoding utf8
        Write-Host "done"
    } catch {
        Write-Host $error
    }
    
}

the command for running the script:

powershell -File "D:\test\exportCSV.ps1" -cInput "D:\test\testFile.xlsx" -cOutput "D:\test\testFile.csv" -cSheet "Sheet 1"

When I run this script directly in cmd it is working without any problems. But when I run in in php with shell_exec() I get following error:

Exception calling "Load" with "1" argument(s): "Exception of type 'System.OutOfMemoryException' was thrown." 

testFile.xlsx has 91,094 KB. When I use a file with only 27,307 KB it is working also with PHP's shell_exec(). I already checked the memory_limit in php.ini (256M) so this shouldn't ne the problem.


Solution

  • The amount of memory the file takes up on disk won't necessarily match the size of the data objects after being imported. Especially if xslx files are compressed (no idea if they are)

    I'd recommend bumping the memory_limit up to 1024M temporarily and trying again with testFile.xlsx to make sure doesn't just require more space to store the imported data in memory.

    If that doesn't work, it could be a bug in the importer that's wasting memory.