简体   繁体   English

PHP使用fopen通过URL下载txt文件。 如何限制下载量?

[英]PHP using fopen to download txt file via URL. How to limit the amount to download?

I have written a php script which parses this text file 我写了一个PHP脚本来解析这个文本文件

http://www.powerball.com/powerball/winnums-text.txt http://www.powerball.com/powerball/winnums-text.txt

Everything is good, but I wish to control the amount that is download ie I do not need every single result maybe max the first 5. At the moment I am downloading the entire file (which is a waste of memory / bandwidth). 一切都很好,但是我希望控制下载量,即,我不需要每个结果都可能只获得前5个结果。此刻,我正在下载整个文件(这浪费了内存/带宽)。

I saw the fopen has a parameter which supposed to limit it but whatever value I placed in has no effect on the amount of text that is downloaded. 我看到fopen有一个应该限制它的参数,但是无论我输入什么值都不会影响下载的文本量。

Can this be done? 能做到吗? Thank you for reading. 感谢您的阅读。

Here is a small snippet of the code in question which is downloading the file. 这是正在下载文件的相关代码的一小段。

<?php

$file = fopen("http://www.powerball.com/powerball/winnums-text.txt","rb");
$rows = array();

    while(!feof($file))
    {
        $line = fgets($file);
        $date = explode("Draw Date",$line);
        array_push($rows,$date[0]);

    }


fclose($file);

?>

Thanks everyone this is the code which just downloads the first row of results 谢谢大家,这是仅下载结果第一行的代码

   while(!feof($file))
        {
            $line = fgets($file);
            $date = explode("Draw Date",$line);
            array_push($rows,$date[0]);

            if(count($rows)>1)
            {
                break;
            }

        }
fclose($file);

You can break whenever you don't need more data. 不需要更多数据时就可以中断。 In this example when count($rows)>100 在此示例中,当count($rows)>100

 while(!feof($file)) {
        $line = fgets($file);
        $date = explode("Draw Date",$line);
        array_push($rows,$date[0]);

       if (count($rows)>100)
          break;

  }

The issue is that your while condition is only met once you've read through to the end of the file. 问题在于,仅当您阅读完文件末尾后,您的while条件才会得到满足。 If you only want to get the first N lines you'll need to change that condition. 如果只想获得前N行,则需要更改该条件。 Something like this might help get you started: 这样的事情可能有助于您入门:

$lineCountLimit = 5;
$currentLineCount = 0;
while($currentLineCount < $lineCountLimit)
{
    $line = fgets($file);
    $date = explode("Draw Date",$line);
    array_push($rows,$date[0]);
    $currentLineCount++;

}

Please try the following recipe to download only a part of the file, like 10 KBytes first, then split to lines and analyze them. 请尝试以下食谱以仅下载文件的一部分,例如先下载10 KB,然后拆分为几行并进行分析。 How to partially download a remote file with cURL? 如何使用cURL部分下载远程文件?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM