0

i want to save data in .txt file when i run my code data not save in txt get output error how can i save this?

Error

Couldn't write values name.txt to file

Template PHP

<?
class Template {
    public $template;

    function load($filepath) {
        $this->template = file_get_contents($filepath);
    }

    function replace($var, $content) {
        $this->template = preg_replace('[{#}(.*){#}]', "", $this->template);
        $this->template = str_replace("#$var#", $content, $this->template);
    }

    function publish() { eval("?>".$this->template."<?"); }

} ?>

PHP

include "template.class.php";

$template = new Template;
$template->load("templates.txt");
$template->replace("name", "Robert Lomees");
$template->publish();

$file = "name.txt";

$savethis=$template->publish();
$fp = fopen($file, "a") or die("Couldn't open $file for writing!");
fwrite($fp, $savethis) or die("Couldn't write values $file to file!");

templates.txt

#name#
11
  • Check that you have enough permission to write to the name.txt file. Commented Dec 17, 2011 at 8:45
  • 1
    Need more information. Your question doesn't show any effort. Commented Dec 17, 2011 at 8:47
  • The second die() should be: or die("Couldn't write values $savethis to file!"); Is $savethis really a string? With content? Commented Dec 17, 2011 at 8:48
  • i need to save this function $template->publish(); Commented Dec 17, 2011 at 8:51
  • @djot: Even fwrite($fp,false); will work. Commented Dec 17, 2011 at 8:51

1 Answer 1

2

Apply handlers as in below code. and try to get where is problem.

<?php
$filename = 'test.txt';
$somecontent = "Add this to the file\n";

// Let's make sure the file exists and is writable first.
if (is_writable($filename)) {

    // In our example we're opening $filename in append mode.
    // The file pointer is at the bottom of the file hence
    // that's where $somecontent will go when we fwrite() it.
    if (!$handle = fopen($filename, 'a')) {
         echo "Cannot open file ($filename)";
         exit;
    }

    // Write $somecontent to our opened file.
    if (fwrite($handle, $somecontent) === FALSE) {
        echo "Cannot write to file ($filename)";
        exit;
    }

    echo "Success, wrote ($somecontent) to file ($filename)";

    fclose($handle);

} else {
    echo "The file $filename is not writable";
}
?>
Sign up to request clarification or add additional context in comments.

1 Comment

Following errors and warnings would tell the OP something equally verbose without creating needless code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.