Reputation: 1955
I am trying to create a file and write to it line by line. When trying to create the file using a file name from a variable, it fails. but if I hard code the file name it works.
The echos are:
Unable to open/create file: CleanStatements\Clean_IRS01HHTAX.TXT
This works:
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.
}
This Does Not
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.
}
Here is the full 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.
}
}
Upvotes: 0
Views: 500
Reputation: 20737
tl;dr
Remove the PHP_EOL
from $this->Name
This is just a guess but I would bet that PHP_EOL
does not contain valid filename characters:
$this->Name = basename($filePath).PHP_EOL;
// which ultimate ends up concatenated in
$this->CleanFilePath
If you really, really, really need to keep it in $this->name
for whatever reason then apply trim()
$cleanFileHandle = fopen( trim( $this->CleanFilePath ), "w") or die("Unable to open/create file: ".trim( $this->CleanFilePath) );
Upvotes: 1