dqh19413 2018-08-21 11:20
浏览 69

PHP - while循环+ fgetcsv到远程文件 - 任何方式避免每次打开和关闭?

I have a peice of PHP script which loops through a directory and looks for filenames present in both the directory and column 1-6 in a CSV file. If it finds one, it checks column 0 of the same row to see if a "Primary" version of the file exists. If it does, it deletes the "secondary" file it's evaluating.

<?php
chdir('../'); // Go up a directory
$fileArray = array_values(preg_grep('/^(\.|\.\.|Removed)$/', scandir('.') , PREG_GREP_INVERT));

foreach ($fileArray as $thisFile)
{
    if (preg_match('/^.*?(?=\.[a-zA-Z0-9]+$)/', $thisFile, $thisFileNoExtension)) // Preg Match the file extension
    {
        $thisFileNoExtension = $thisFileNoExtension[0]; // Give the file extension it's own string
    }
    else
    {
        $thisFileNoExtension = $thisFile; // If it's a directory
    }

    // Let the user know what file is being evaluated
    echo "\033[35m{$thisFileNoExtension} ... \033[0m";

    $csvManualRegionDupes = fopen("--- HYPERLINK TO REMOTE GOOGLE SHEETS CSV FILE ---", "r");

    while ($csvRow = fgetcsv($csvManualRegionDupes))
    {
        if (in_array($thisFileNoExtension, array_slice($csvRow, 1, 6)))
        {
            $fileCheck = preg_grep('/' . preg_quote($csvRow[0]) . '/', $fileArray); //
            if ($fileCheck)
            {
                echo "\033[36mis on the Manual Region Dupes list and primary version detected. Moved to Removed folder.
\033[0m";
                rename("$thisFile", "Removed/$thisFile");
            }
            else
            {
                echo "\033[31mis on the Manual Region Dupes list but primary version is missing. Kept for now.
\033[0m";
                continue 2;
            }
        }
    }
    fclose($csvManualRegionDupes);

echo "\033[34mScanned and is OK.
\033[0m";
}
?>

It used to work well, however now that I have put $csvManualRegionDupes to point towards a remote file, it's taking a long time to get through the loop. I think this is beacuse fopen and fclose is being run for every $thisFile. Is there a way of opening this remote file only once and still completing the foreach and while loops properly? I have tried tinkering with it and I keep breaking the functionality.

Many thanks!

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
    • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
    • ¥16 mybatis的代理对象无法通过@Autowired装填
    • ¥15 可见光定位matlab仿真
    • ¥15 arduino 四自由度机械臂
    • ¥15 wordpress 产品图片 GIF 没法显示
    • ¥15 求三国群英传pl国战时间的修改方法
    • ¥15 matlab代码代写,需写出详细代码,代价私
    • ¥15 ROS系统搭建请教(跨境电商用途)
    • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。