我正在尝试创建一个文件并逐行写入。当尝试使用变量中的文件名创建文件时,会失败。但如果我对文件名进行硬编码,它就会起作用。
回声为:
无法打开/创建文件:CleanStatements\Clean_IRS01HTAX.TEXT
这是有效的:
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.
}
}
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) );