dpz7935
2015-09-16 11:07
浏览 93
已采纳

php在文本日志文件中输出格式化数组和对象等

Should be a pretty obvious answer, but I have spent several hours looking at existing similar questions and none are working for me

My code generates logfiles for (manual) debugging etc If I use print_r($array,TRUE) to capture the output from an array as a string and then echo with <pre> tags to display that on screen, it's really easy to view and understand what's going on.

However, when I write the same info to the logfile, fwrite doesn't preserve the line break and indentation formatting so there is a splurge of info that takes significant amounts of time to make sense of, esp larger arrays and objects.

I have tried using output buffer

$string=print_r($array,TRUE);
ob_start();
echo "<pre>$string</pre>";
$outputBuffer = ob_get_contents();
ob_end_clean();
fwrite($handle,$outputBuffer);

However, all that's now happening is that I see the <pre> tags added into the basic, non-layout output

e.g.

<pre>DOING QUERY: SELECT * FROM event_triggers WHERE DateTime<='2015-09-16 13:04:30'</pre><pre>Completed checking for event triggers</pre>

图片转代码服务由CSDN问答提供 功能建议

应该是一个非常明显的答案,但我花了几个小时查看现有的类似问题,没有一个对我有用

我的代码为(手动)调试等生成日志文件 如果我使用print_r($ array,TRUE)将数组的输出捕获为字符串,然后使用&lt回显 ; pre&gt; 标签在屏幕上显示,很容易查看和理解正在发生的事情。

但是,当我将相同的信息写入日志文件时,fwrite不会 不保留换行符和缩进格式,这样就会消耗大量信息,需要花费大量时间才能理解,特别是更大的数组和对象。

我尝试过使用输出缓冲区

  $ string = print_r($ array,TRUE); 
ob_start(); 
echo“&lt; pre&gt; $ string&lt; / pre&gt;”; 
 $ outputBuffer =  ob_get_contents(); 
ob_end_clean(); 
fwrite($ handle,$ outputBuffer); 
   
 
 

然而,现在发生的一切就是我 将&lt; pre&gt; 标签添加到基本的非布局输出中

例如

 &lt  ; pre&gt; DOING QUERY:SELECT * FROM event_triggers WHERE DateTime&lt; ='2015-09-16 13:04:30'&lt; / pre&gt;&lt; pre&gt;已完成对事件触发器的检查&lt; / pre&gt; 
    
 
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • doubai9014 2015-09-16 11:12
    已采纳

    You can't just add HTML tags to a document, open it in an editor expect HTML tags to be rendered correctly.

    You either have to setup your log file as a HTML file (doesn't neccessarily have to be valid, so just add .html to the file name and open it in the browser) or use var_dump to echo out the variables.

    打赏 评论
  • dor65412 2015-09-16 11:44

    Rename file to .html extension and just open with a browser. Browser will detect it with line break html document. <pre></pre> will output like <p></p> in the browser.

    打赏 评论

相关推荐 更多相似问题