Skip to content
PHP Logo

How can a PHP-generated file be saved without the PHP code?

When generating a file using PHP, the PHP code itself may be included in the file if not handled correctly. To save a PHP-generated file without the PHP code, you can use output buffering to capture the generated content and then save it to a file using file handling functions. By buffering the output, you can separate the content from the PHP code and save only the desired content to a file.

php
<?php

ob_start(); // Start output buffering

// Generate content here
echo "Hello, this is the content of the file.";

$content = ob_get_clean(); // Get the buffered content and clean the buffer

// Save the content to a file
$file = fopen("output.txt", "w");
fwrite($file, $content);
fclose($file);

echo "File saved successfully!";