How can PHP developers adapt their code to handle different formatting requirements for browsers and text files?

PHP developers can use conditional statements to detect the type of output required (browser or text file) and adjust the formatting accordingly. They can use functions like header() to set the content type for browser output or file handling functions like fopen() and fwrite() to write formatted data to a text file.

<?php
$outputType = 'browser'; // Set the output type to either 'browser' or 'file'

if ($outputType === 'browser') {
    header('Content-Type: text/html');
    echo '<h1>Hello, World!</h1>';
} elseif ($outputType === 'file') {
    $file = fopen('output.txt', 'w');
    fwrite($file, 'Hello, World!');
    fclose($file);
}
?>