【问题标题】:How do I edit multiple .txt files with different names in a folder?如何在一个文件夹中编辑多个不同名称的 .txt 文件?
【发布时间】:2020-03-09 13:20:56
【问题描述】:

我有一个包含多个 .txt 文件的文件夹:

A500_1.txt

A500_2.txt

A700_1.txt

A700_2.txt

A900_1.txt

...

在每个 .txt 文件中都有:

PRXC1_|TB|CCAAO9-RC|9353970324463|24.99

PRXC1_|TB|CFEXK4-RC|9353970294766|84.99

PRXC1_|TB|CFEXK4-RC|9353970294773|84.99

...

我希望你:

  • 如果文件名以 A500 开头_ 将“TB”替换为“MD”

  • 如果文件名以 A700 开头_ 将“TB”替换为“JB”

  • 如果文件名发件人代码以 A900 开头_ 将“TB”替换为“LD”

我编写了这个函数,但它只是在项目的根目录下创建了一个空的 A500_2.TXT 文件并显示:

Warning: file_get_contents(A500_2.TXT): failed to open stream:

我的错误在哪里?

<?php

function processFile( $path ) {

   $dir    = './test/';
   $allFiles = scandir($dir);

   foreach($allFiles as $file) {

       $filename = basename( $file );

        if ( ! in_array($file,array(".","..")))
      { 

       //read the entire string
       $str = file_get_contents( $file );

       // var_dump($str);

       // replace something in the file string
       if ( strpos( $filename, 'A500_' ) === 0 ) {

           $str = str_replace( 'TB', 'MD', $str );

       } else if ( strpos( $filename, 'A700_' ) === 0 ) {

           $str = str_replace( 'TB', 'JB', $str );

       } else if ( strpos( $filename, 'A900_' ) === 0 ) {

           $str = str_replace( 'TB', 'LD', $str );

       } else {
           // Return false if we don't know what to do with this file
           return false;
       }

       //write the entire string    
       $writeResult = file_put_contents( $file, $str );

       //return true after a file is written successfully, or false on failure
       return $writeResult >= 0;

  }
  }
}

if(processFile( './test/' )) echo "good!";
?>

【问题讨论】:

  • 你的PHP Current Working Directory 是什么?您应该给 PHP 一个绝对目录来打开该文件,因为“A500_2.TXT”只是一个与正在运行的脚本位于同一文件夹中的文件。
  • 不应该是file_get_contents($dir.$file)吗?
  • 如果我将 file_get_contents($dir.$file) 放在文件夹的根目录下,它将通过 MD 更改 TB 而不是在我的测试文件夹中创建文件 A500_2.TXT。
  • Eric,this answer 是对另一个问题的回答,但同样的事情对你也有用——你应该使用 absolute filepathing 和 $_SERVER['DOCUMENT_ROOT']。如果这仍然不起作用,然后查看权限问题
  • @Eric27 “但不在我的测试文件夹中”因为您需要在您的 file_put_contents() 通话中做同样的事情。

标签: php file-get-contents str-replace


【解决方案1】:

file_get_contents 警告和正在创建的空白文件都归结为同一个问题 - scandir 返回只是文件名,而不是当前运行脚本的相对路径。

我猜您希望它返回相对路径,这就是您在循环顶部调用 basename 的原因。实际上,您的 $file$filename 参数将始终设置为相同的值。

最快的解决方案是在处理其他任何内容之前在$file 前面加上扫描的目录名称:

$file = $dir . $file;

这应该修复读取和写入调用。

【讨论】:

  • 它改变了我的文件 A500_2.TXT 但不是我文件夹中的所有文件
  • @Eric27 哦,对不起,我应该注意到这一点。您的函数在 foreach 循环的底部设置为 return,这意味着它只能处理一个文件。如果您希望它实际处理整个文件夹,则需要将其删除。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-11
  • 1970-01-01
  • 1970-01-01
  • 2020-03-31
  • 1970-01-01
相关资源
最近更新 更多