Current Location: Home> Latest Articles> How to Save Content Captured by ob_get_contents() to a File?

How to Save Content Captured by ob_get_contents() to a File?

gitbox 2025-09-24
<span><span><span class="hljs-meta">&lt;?php</span></span><span>
</span><span><span class="hljs-comment">// This part is unrelated to the main content and can be other logic or comments in the program</span></span><span>
</span><span><span class="hljs-comment">// For example, initialization settings, file inclusions, etc.</span></span><span>
</span><span><span class="hljs-meta">?&gt;</span></span><span>
<p><hr></p>
<p></span><?php<br>
/**</p>
<ul>
<li>
<p>What are the specific steps to save content captured by ob_get_contents() to a file?</p>
</li>
<li></li>
<li>
<p>In PHP, ob_get_contents() is used to get the content from the current buffer.</p>
</li>
<li>
<p>If you enable output buffering using ob_start(), the page output is not directly sent to the browser,</p>
</li>
<li>
<p>but is stored in the buffer.</p>
</li>
<li>
<p>At this point, you can use ob_get_contents() to retrieve the content and save it to a file.</p>
</li>
<li></li>
<li>
<p>The specific steps are as follows:<br>
*/</p>
</li>
</ul>
<p>// 1. Start output buffering<br>
ob_start();</p>
<p>// 2. Output the content you want to capture, such as HTML, text, or program output<br>
echo "<h1>Welcome to the Output Buffering Example</h1>";<br>
echo "<p>This content will be captured and saved to a file.</p>";</p>
<p>// 3. Use ob_get_contents() to get the buffer content<br>
$content = ob_get_contents();</p>
<p>// 4. Close and clean the buffer<br>
ob_end_clean(); // Alternatively, use ob_end_flush(), but usually clean the buffer</p>
<p>// 5. Write the captured content to a file<br>
$file = 'output.html';<br>
file_put_contents($file, $content);</p>
<p>// 6. Output a success message (optional depending on your needs)<br>
echo "Content has been successfully saved to file: {$file}";</p>
<p>/**</p>
<ul data-is-last-node="" data-is-only-node="">
<li>
<p>The above steps explain how to save content captured by ob_get_contents() to a file.</p>
</li>
<li>
<p>The key points are:</p>
</li>
<li>
<ul>
<li>
<p>Use ob_start() to start buffering</p>
</li>
</ul>
</li>
<li>
<ul>
<li>
<p>Output the content you want to capture</p>
</li>
</ul>
</li>
<li>
<ul>
<li>
<p>Use ob_get_contents() to retrieve the content</p>
</li>
</ul>
</li>
<li>
<ul>
<li>
<p>Close the buffer to prevent repeated output</p>
</li>
</ul>
</li>
<li>
<ul>
<li>
<p>Write the content to a file</p>
</li>
</ul>
</li>
<li></li>
<li data-is-last-node="">
<p data-is-last-node="">This method is commonly used for generating static pages, caching page content, logging, etc.<br>
*/<br>
?><br>
</span>