Reputation: 11
I want to open the .xml file and write the content of the $xml_doc
variable into the file. The problem is, when the file is empty, it refuses to write. It only writes when there is already some text (abc123 for example). I tried to change mode of fopen function to a, a+, w, w+, and w, w+ are simply erase the file content but write nothing.
if($telecharger) {
// Creation du fichier
$nom = "PRELEVEMENT";
$filename= "/home/alc/alcg_si/alcgroup/intranet/documents/prelevement_xml/".$nom."__".$date_prev.".xml";
try {
$file = fopen($filename, 'r+') or die("Error: can't open file.");
chmod($filename, 0777);
fwrite($file, '$xml_doc') or die("Error: can\'t write in file.");
fclose($file);
} catch (Exception $e) {
echo "MERDEEEE<br>";
echo 'Caught exception: ', $e->getMessage(), "\n";
}
Upvotes: 1
Views: 325
Reputation: 782166
File permissions are checked when opening the file. If the file permissions don't allow writing, you need to call chmod()
before calling fopen()
.
You can also replace all the code that calls fopen
, fwrite
, and fclose
with a single call to file_put_contents()
.
And don't put the variable $xml_doc
in single quotes, that prevents expanding the variable. It will write the literal string $xml_doc
to the file.
if($telecharger) {
// Creation du fichier
$nom = "PRELEVEMENT";
$filename= "/home/alc/alcg_si/alcgroup/intranet/documents/prelevement_xml/".$nom."__".$date_prev.".xml";
try {
if (file_exists($filename)) {
chmod($filename, 0644) or die("Error: can't change file permissions");
}
file_put_contents($filename, $xml_doc) or die("Error: can\'t write in file.");
} catch (Exception $e) {
echo "MERDEEEE<br>";
echo 'Caught exception: ', $e->getMessage(), "\n";
}
Upvotes: 0