【问题标题】:Copy a file's text to another file PHP将文件的文本复制到另一个文件 PHP
【发布时间】:2021-02-28 08:16:47
【问题描述】:

我想将内容从 (Bazamod.txt) 复制到 (compile.txt) 但出现此错误:

警告:fopen(LicenteSi/Test/compile.txt):无法打开流:否 这样的文件或目录在 /storage/ssd3/361/16261361/public_html/createL.php 在第 137 行

警告:fwrite() 期望参数 1 是资源,布尔值在 /storage/ssd3/361/16261361/public_html/createL.php 在第 141 行

Function create_compile_mod($Licence_Name, $Path){
      $FilePath = "$Path/compile.txt";
        $myFile = fopen($FilePath, "r+");
        
            copy("bazamod/Bazamod.txt", $FilePath);
        
        fwrite($myFile, $FilePath);
    }

谢谢!

【问题讨论】:

  • 使用file_get_contentsfile_put_contents函数
  • 你是如何调用函数的?您能否将其添加到问题中并可能解释/显示目录结构?
  • bluepinto 帮忙,我成功完成了!非常感谢!
  • 使用file_get_contentsfile_put_contents的组合意味着你将所有内容读入内存。适合琐碎的内容,尽管它显然比内部文件系统操作慢得多。但这不会扩展。相反,您应该尝试了解为什么您的copy 方法不起作用。并修复它。这很可能是路径问题...

标签: php


【解决方案1】:

如果您需要做的只是将Bazamod.txt 的内容复制到compile.txt,通过提供compile.txt 的路径作为参数,那么下面的函数就可以解决问题:

<?php
function create_compile_mod($Path)
{
    $fileContents = file_get_contents("bazamod/Bazamod.txt");
    $fileHandle = fopen($Path . "/compile.txt", "r+");
    fputs($fileHandle, $fileContents);
    fclose($fileHandle);
}
?>

我没有包含您的 $Licence_Name 参数,因为它似乎没有被使用,但您可以调整上面的代码以满足您的需求。

请记住,上面的代码将复制Bazamod.txt 的全部内容并替换compile.txt 的现有内容。如果您只想添加新文本,请使用"a" 访问模式而不是指定的"r+",文本将自动添加到文档底部。

如果您需要在特定行添加,您可以选择:

<?php
function create_compile_mod($Path, $lineIndex)
{
    $oldContents = file_get_contents("bazamod/Bazamod.txt");
    $compileArray = file($Path . "compile.txt");

    array_splice($compileArray, $lineIndex, 0, $oldContents); 
    $newContent = implode(PHP_EOL, $compileArray);

    $compileFh = fopen($Path . "compile.txt", "r+");
    fputs($compileFh, $newContent);
}
?>

将您的 $lineIndex 指定为您希望放置内容的行号(从第 0 行开始),并像 create_compile_mod("./", 4) 一样调用您的函数。

【讨论】:

    猜你喜欢
    • 2014-02-26
    • 1970-01-01
    • 2014-12-05
    • 2020-07-30
    • 1970-01-01
    • 2013-04-26
    • 1970-01-01
    • 2015-02-01
    • 2013-02-26
    相关资源
    最近更新 更多