我正在尝试创建文件并逐行写入。尝试使用变量中的文件名创建文件时,它失败。但是,如果我对文件名进行硬编码,它就可以工作。
回声是:
无法打开/创建文件: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 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.
}
}
答案 0 :(得分:1)
tl; dr
从PHP_EOL
删除$this->Name
这只是一个猜测,但我敢打赌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) );