写不写

时间:2011-09-28 04:34:54

标签: php fwrite

 $fp = fopen('log.txt', 'w');
 fwrite($fp, 'Missing gallery image for: ' . $row['toolbar_id'] . '\n');

上面的代码没有写入文件。 $row['toolbar_id']是每个循环的a值。有什么建议?没有PHP错误,因为文件打开了,因为我调试了那个部分。

3 个答案:

答案 0 :(得分:6)

试试这个以获得额外担保

ini_set('display_errors', 'On');
error_reporting(E_ALL);

$fp = fopen('log.txt', 'ab');
if (false === $fp) {
    throw new RuntimeException('Unable to open log file for writing');
}

$bytes = fwrite($fp, 'Missing gallery image for: ' . $row['toolbar_id'] . PHP_EOL);
printf('Wrote %d bytes to %s', $bytes, realpath('log.txt'));
fclose($fp);

编辑:将“写入”标志( w )更改为“追加”( a ),因为截断日志文件不听起来像个好主意

答案 1 :(得分:0)

https://bugs.php.net/bug.php?id=48607 fwrite和ftp有一个php bug,这意味着在fwrite之后直接调用fclose时有时候不会写入最后一块文件 睡觉(1);在fclose修复问题之前,或者在你的情况下,在fclose之前记录到文件也可以阻止它

发布以供将来参考!

答案 2 :(得分:0)

 <?php
    $filename = 'log.txt';
    $somecontent = "Missing gallery image for: ";
    if($row['toolbar_id'] != "") 
    { 
        $somecontent .= $row['toolbar_id'];
    }

   if (is_writable($filename)) {


        if (!$handle = fopen($filename, 'a')) {
             echo "Cannot open file ($filename)";
             exit;
        }


        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";
    }
    ?>

试试这段代码...... !!