PHP从几个文本文件中读取数据,从所有文件中输出某一行?

PHP从几个文本文件中读取数据,从所有文件中输出某一行?,php,file,Php,File,我正试图编写一个脚本,读取25个重文本文件的内容(每个文件大约100行)。我希望我的脚本输出每个文本文件的第5行。我还在windows工作站上工作(在本地环境中使用Apache进行测试) 每个文本文件都位于同一个目录(即products/product1.txt)中,我想这样会更容易 第5行的每个文本文件如下所示(具有不同的描述): 我还想知道,在实现上述功能后,是否有可能让脚本删除文本“Product Desc:”,以便只显示实际的产品描述 请提供任何代码示例,因为我是noobie:)$dir

我正试图编写一个脚本,读取25个重文本文件的内容(每个文件大约100行)。我希望我的脚本输出每个文本文件的第5行。我还在windows工作站上工作(在本地环境中使用Apache进行测试)

每个文本文件都位于同一个目录(即products/product1.txt)中,我想这样会更容易

第5行的每个文本文件如下所示(具有不同的描述):

我还想知道,在实现上述功能后,是否有可能让脚本删除文本“Product Desc:”,以便只显示实际的产品描述

请提供任何代码示例,因为我是noobie:)

$dir=opendir('directory');
而($file=readdir($dir)){
如果($file!=“.”或$file!=“.”){
$opened=文件($file);
echo$已打开[4]。“
”; } }
PHP加载多个文件:

<?php
date_default_timezone_set("America/Edmonton");
$products=array();
$dir="../products/"; //Set this for whatever your folder


function getProduct($file) {
    $fp=fopen($file,"r");
    //Read five lines
    for ($j=0;$j<5;$j++) $line=fgets($fp);
    $GLOBALS["products"][]=substr($line,14);//Since products is a global var
    fclose($fp);
}

$dp=opendir($dir);
while (($file = readdir($dp)) !== false) {
  if ($file!="." && $file!="..")
    getProduct($dir.$file);
}
closedir($dp);

//Review the product list
print_r($products);
?>
line 1
line 2
line 3
line 4
Product Desc: iPhone
line 6
快捷方式:

<?php
date_default_timezone_set("America/Edmonton");
$products=array();
$dir="../products/"; //Set this for whatever your folder


function getProduct($file) {
    $fp=fopen($file,"r");
    //Read five lines
    for ($j=0;$j<5;$j++) $line=fgets($fp);
    $GLOBALS["products"][]=substr($line,14);//Since products is a global var
    fclose($fp);
}

$dp=opendir($dir);
while (($file = readdir($dp)) !== false) {
  if ($file!="." && $file!="..")
    getProduct($dir.$file);
}
closedir($dp);

//Review the product list
print_r($products);
?>
line 1
line 2
line 3
line 4
Product Desc: iPhone
line 6
因为我们只需要第五行,所以我们使用
$j
循环来读取前五行,每行都覆盖最后一行。如果文件少于五行,您将从
$line
中得到一个
null
。。。您应该对此进行测试(而不是将其添加到产品列表中)。最后,因为我们现在知道了字符串“
Product Desc:
”(按照您编写的方式)的长度,所以我们可以将该行的第一部分扔掉。这并不可怕,最好使用正则表达式或字符串解析来确保有正确的单词,然后使用冒号后面的数据。还是。。。它回答了您最初的问题;)

您说过可能会有更多的行,这种方法只会将前5行加载到内存中(每个都覆盖最后一行),并在到达第五行时停止。。。这意味着与将整个文件读入数组(
文件
)然后只使用第5行相比,性能和内存都有很大的优势

设计决策:

<?php
date_default_timezone_set("America/Edmonton");
$products=array();
$dir="../products/"; //Set this for whatever your folder


function getProduct($file) {
    $fp=fopen($file,"r");
    //Read five lines
    for ($j=0;$j<5;$j++) $line=fgets($fp);
    $GLOBALS["products"][]=substr($line,14);//Since products is a global var
    fclose($fp);
}

$dp=opendir($dir);
while (($file = readdir($dp)) !== false) {
  if ($file!="." && $file!="..")
    getProduct($dir.$file);
}
closedir($dp);

//Review the product list
print_r($products);
?>
line 1
line 2
line 3
line 4
Product Desc: iPhone
line 6

看起来您正在构建产品目录,最好使用数据库来存储这些数据。不一定是个大问题(MySQL、PostgreSQL),它可以像SQLite一样简单。

所以这基本上是三个部分:(1)需要循环遍历目录,(2)读取每个文件的第五行,(3)需要读取该行中冒号后的部分

  // open the products directory  
  $fileHandle = opendir('products');

  // create an array to store the file data
  $files = array();

  // create an array to store products
  $products = array();

  if ($fileHandle) {
    // loop through each file
    while ( false !== ($singleFile = readdir($fileHandle)) ) {

      // use file() to read the lines of the file
      $lines = file($singleFile);

      // store the fifth line in each file (the array starts at 0)
      $productDescription = explode(":",$lines[4]);
      $products[] = productDescription[1]; // the bit after the colon
    }
  }

  // this should show you an array of the products
  print_r($products);
回答:(底部的原始代码)

这个过程有三个方面。

  • 获取目录中的所有文件名
  • 读取每个文件的第五行
  • 在结肠后分开
  • 我的方法有很好的文档记录,可以理解。它使用函数来完成流程的特定部分。它很容易理解正在发生的事情,同时也相当健壮


    完成工作的功能:

    <?php
        function readAfterColon($string) {
        /**
         * @param string $string The string you'd like to split on.
         * 
         * @return string The data after the colon.  Multiple colons work just fine.
         */
        $array = explode(":",$string, 2);
        return isset($array[1]) ? $array[1] : '';
        }
    
        function readLine($lineNumber, $fileName) {
            /**
             * @param int $lineNumber The line number you want to read from the file.
             * @param string $fileName The string representing the file you wish to open.
             * 
             * @return string The contents of the line in the file.
             */
            $file = file($fileName);
            return $file[$lineNumber-1];
        }
    
        function readLineFrom($lineNumber, $fileNames) {
            /**
             * @param int $lineNumber The line number you want to read from the file.
             * @param string|array $files Either a string for the file you want to open, or an array of filenames.
             * 
             * @return array An associative array of the filename to the contents of the line.
             */
            $lines = array();
            if(is_array($fileNames)) {
                foreach($fileNames as $fileName) {
                    $lines[$fileName] = readLine($lineNumber, $fileName);
                }
            } else {
                $lines[$fileNames] = readLine($lineNumber, $fileNames);
            }
    
            return $lines;
        }
    
        function getFileNamesFromDirectory($directory = '.') {
            /**
             * @param string $directory The path to directory you'd like to get filenames from. Defaults to current directory.
             * 
             * @return array An array of filenames.  Empty if there are no files.
             */
            $fileNames = array();
            if ($handle = opendir($directory)) {
                while (false !== ($file = readdir($handle))) {
                    if ($file != "." && $file != "..") {
                        $fileNames[] = $directory . $file;
                    }
                }
                closedir($handle);
            }
            return $fileNames;
        }
    
    ?>
    

    有没有更有效的方法?如果产品数量继续增长。i、 到圣诞节我们可能会有100多个:)嗯,你错过了很多步骤
    fopen
    只返回一个资源,不返回文件内容;)@这看起来很完美。请原谅我的愚蠢,但你能告诉我在目录引用中的位置吗?我是一名老派的宏excel程序员:)@JaneKealum:change
    'file.$I
    改为
    'directory/file.$I
    @genesis:看起来很有希望,但我在html页面中收到一个空白输出。而且我肯定不会指向目录中的特定文件?因此,它会是“directory/*.txt”吗?我也不能让它工作:(您需要读取目录中的所有文件吗?或者,更具体地说,该目录中是否有您不想读取的文件?我有一个示例,可以读取每个文件及其所有内容,就是这样。但是,它完全是一团糟,而且非常“PHP繁忙”。我希望更有经验的开发人员能够想出一些更具创造性的方法ve!@Matthew,需要读取目录中的所有文件。希望有帮助吗?这会使它变得更容易/更困难吗?它会使它变得更简单。您可以进一步查看目录中的特定文件(可能是扩展名),但循环遍历整个位会使代码更轻一些。感谢对$j的深入详细信息和易于理解的描述,这对我来说是新的:)这很好,但是,你能编辑答案吗,这样我就不必特别命名目录中的每个文件了?例如,到了圣诞节,我们可能有100多个产品!再次感谢mm..现在有问题获取数组ti显示任何内容。simpy现在得到一个空白屏幕。没有看到文件中的输入?它们在你更改之前Howver:我认为我很接近,但是我没有输出任何值?我正在获取数组列表,看到有25个文件。但是,每个文件的第5行的值没有字符串输出。这可能与“产品”的全局变量有关吗?我不知道是这样的…@JaneKealum我想我应该添加一些调试:fir
    getProduct
    add
    echo“get$file
    ”;
    (这将显示正在读取的文件-应输出25个名称)。在同一函数中的
    for
    之后,添加
    echo“$line
    ”;
    以查看正在捕获的行。。如果它关闭(不是第五行?)相应地调整
    $j
    。很好,很干净,我理解它在这里的工作原理,尽管我认为可能存在错误?我现在收到一个服务器500错误。我尝试了:opendir('products')和opendir('products/')。您可以始终从products目录中运行此代码并使用opendir(“.”)这正是我在寻找的解释。这是非常感谢,我只是花了30分钟仔细分析代码,以便更好地理解语法…但是有问题;脚本正确地输出文件名(全部25个),但是没有为