【问题标题】:What does this get_text function do?这个 get_text 函数有什么作用?
【发布时间】:2013-07-06 19:23:47
【问题描述】:

Panique 很好地回答了这个线程上的问题:PHP directory list from remote server

但他创建了一个我根本不理解的函数,并希望得到某种解释。比如随机的 8192 数字是什么?

function get_text($filename) {

    $fp_load = fopen("$filename", "rb");

    if ( $fp_load ) {

            while ( !feof($fp_load) ) {
                $content .= fgets($fp_load, 8192);
            }

            fclose($fp_load);

            return $content;

    }
}

【问题讨论】:

  • 不要在fopen() 调用中将$filename 放在引号中。这没有多大意义。
  • 我只是使用了 Panique 使用的东西(如前所述),无论哪种方式都有效

标签: php


【解决方案1】:

它加载路径在$filename 中的文件并返回它的内容。 8192 不是随机的。这意味着以 8kb 的块读取文件。

只要文件未被完全读取,while 循环就会运行。每次迭代都会将文件的最新 8kb 添加到函数末尾返回的$content

【讨论】:

    【解决方案2】:

    它加载文件的数据。

    For example, what's with the random 8192 number?

    http://php.net/manual/en/function.fgets.php

    读取结束时长度 - 1 个字节已被读取,或换行符( 包含在返回值中)或 EOF(以先到者为准)。 如果没有指定长度,它将一直从流中读取,直到 它到达了行尾。

    【讨论】:

      【解决方案3】:

      分解:

      function get_text($filename) { //Defines the function, taking one argument - Filename, a string.
      
          $fp_load = fopen("$filename", "rb"); //Opens the file, with "read binary" mode.
      
          if ( $fp_load ) { // If it's loaded - fopen() returns false on failure
      
                  while ( !feof($fp_load) ) { //Loop through, while feof() == false- feof() is returning true when finding a End-Of-File pointer
                      $content .= fgets($fp_load, 8192); // appends the following 8192 bits (or newline, or EOF.)
                  } //Ends the loop - obviously.
      
                  fclose($fp_load); //Closes the stream, to the file.
      
                  return $content; //returns the content of the file, as appended and created in the loop. 
      
          } // ends if
      } //ends function
      

      我希望这会有所帮助。

      详细说明8192:

      当读取到 length - 1 个字节、换行符(包含在返回值中)或 EOF(以先到者为准)时,读取结束。如果没有指定长度,它将继续从流中读取,直到到达行尾。

      来自:http://php.net/manual/en/function.fgets.php

      【讨论】:

        猜你喜欢
        • 2017-07-25
        • 2014-06-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-18
        • 2013-10-21
        • 1970-01-01
        相关资源
        最近更新 更多