简体   繁体   English

PHP使用fwrite记录到文件

[英]Php logging to a file with fwrite

Question 1: What is the best way to write multiple variables? 问题1:编写多个变量的最佳方法是什么?

I'm currently writing them like this. 我目前正在这样写它们。

fwrite($fp, $var1);
fwrite($fp, $var2);
fwrite($fp, $var3);
    ...etc

And that makes one long healthy string of output. 这样就形成了一个长期有效的输出字符串。

Question 2: How do I add line breaks and comments without writing something like: 问题2:如何在不编写类似以下内容的情况下添加换行符和注释:

fwrite($fp, 'var1:');
fwrite($fp, &var1); 
<br>?

Concatenation! 级联! You can basically combine a bunch of variables/strings into one big string, and print it all in a single fwrite. 您基本上可以将一堆变量/字符串组合成一个大字符串,并在单个fwrite中全部打印出来。

ie: 即:

fwrite($fp, "var1: " . $var1 . "\r\nvar2: " . $var2 );

etc 等等

What the best solution would be depends on the use-case. 最佳解决方案将取决于用例。 If you could be a bit more clear about what kind of data you are writing we could give you an advise. 如果您可以更清楚地知道要写入哪种数据,我们可以为您提供建议。 But foremost take a look at all different file system functions . 但是首先要看一下所有不同的文件系统功能 There's probably one you like :) 你可能喜欢一个:)

A few options: 一些选择:

Write away an array 写出一个数组

$data = array('value 1', 'value 2', 'value 3');
file_put_contents(realpath('path/to/file'), $data);

Or an indexed array 或索引数组

$data = array('var 1' => 'value 1', 'var 2' => 'value 2', ...);
foreach($data as $var => $value) {
    fwrite($fp, $var .': '. $value);
}

Or if you want to include newlines ( \\n ): 或者,如果要包括换行符( \\n ):

$data = array('value 1', 'value 2', 'value 3');
fwrite($fp, implode("\n", $data));

options are numerous... more details = better assistance ;) 选项很多...更多细节=更好的帮助;)

Another option might be to look in to using Monolog ( https://github.com/Seldaek/monolog ). 另一个选择可能是使用Monolog( https://github.com/Seldaek/monolog )。 Add something like the following at the start of your script: 在脚本的开头添加如下内容:

use Monolog\Logger;
use Monolog\Handler\StreamHandler;

// create a log channel
$log = new Logger('name');
$log->pushHandler(new StreamHandler('path/to/your.log', Logger::DEBUG));

Then whenever you want to output something add: 然后,每当您要输出内容时,请添加:

// add records to the log
$log->addDebug($var1);
$log->addDebug($var2);
$log->addDebug($var3);

It's a bit more work initially but you end up with a much more flexible solution in the long run. 最初需要做更多的工作,但从长远来看,您最终将获得更灵活的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM