fopen 不允许创建文件名变量

fopen not allowing a variable for file name to create

我正在尝试创建一个文件并逐行写入。尝试使用变量中的文件名创建文件时失败。但如果我对文件名进行硬编码,它就可以工作。

回声是:

Unable to open/create file: CleanStatements\Clean_IRS01HHTAX.TXT

这个有效:

if ($handle) {
        $cleanFileHandle = fopen( "CleanStatements\Clean_IRS01HHTAX.TXT", "w") or die("Unable to open/create file: ".$this->CleanFilePath);
        while (($line = fgets($handle)) !== false) {
            fwrite($cleanFileHandle, $line);
        }
        fclose($cleanFileHandle);
        fclose($handle);
    } else {
        // error opening the file.
    }

这不是

if ($handle) {
        $cleanFileHandle = fopen( $this->CleanFilePath, "w") or die("Unable to open/create file: ".$this->CleanFilePath);
        while (($line = fgets($handle)) !== false) {
            fwrite($cleanFileHandle, $line);
        }
        fclose($cleanFileHandle);
        fclose($handle);
    } else {
        // error opening the file.
    }

这里是完整的 class:

/**
 * Class StatementFile
*/
class StatementFile
{
var $Name;
var $FilePath;
var $Type;
var $CleanFileName;
var $CleanFilePath;

function __construct($filePath){
    $this->Name = basename($filePath).PHP_EOL;
    $this->FilePath = 'Statements\'.$filePath;
    $this->Type = null;
    $this->CleanFileName = "Clean_".$this->Name;
    $this->CleanFilePath = "CleanStatements\" . $this->CleanFileName;
}

function cleanStatement(){
    $handle = fopen($this->FilePath, "r");
    echo "Opening file: ".$this->FilePath ."<br/>";
    if ($handle) {
        $cleanFileHandle = fopen( $this->CleanFilePath, "w") or die("Unable to open/create file: ".$this->CleanFilePath);
        while (($line = fgets($handle)) !== false) {
            // process the line read.
            // clean line here
            fwrite($cleanFileHandle, $line);
        }
        fclose($cleanFileHandle);
        fclose($handle);
    } else {
        // error opening the file.
    }
}

tl;dr

$this->Name

中删除 PHP_EOL

这只是一个猜测,但我敢打赌 PHP_EOL 不包含有效的文件名字符:

$this->Name = basename($filePath).PHP_EOL;
// which ultimate ends up concatenated in
$this->CleanFilePath

如果您出于任何原因真的、真的、真的需要将其保留在 $this->name 中,请应用 trim()

$cleanFileHandle = fopen( trim( $this->CleanFilePath ), "w") or die("Unable to open/create file: ".trim( $this->CleanFilePath) );