How to Indent Lines in a File using PHP

Indenting lines in a file using PHP code is quite easy. The steps are:

  1. Open the file and read its contents line by line.
  2. For each line, prepend the desired amount of indentation (like spaces or tabs).
  3. Write the indented lines back to the file or to a new file.

Here's the PHP script:


$file = 'path/to/your/file.txt'; // Replace with your file path
$indentation = ' '; // Four spaces for indentation, you can use "\t" for a tab

// Read the file into an array, each line as an array element
$lines = file($file, FILE_IGNORE_NEW_LINES);

// Indent each line
foreach ($lines as &$line) {
    $line = $indentation . $line;

// Write the indented lines back to the file
file_put_contents($file, implode("\n", $lines));


This script will read each line from the specified file, prepend the indentation (in this case, four spaces) to each line, and then write the indented lines back to the file. You can modify the $indentation variable to change the type and amount of indentation as required.

Keep in mind that this script overwrites the original file. If you want to keep the original file unchanged and save the indented content to a new file, specify a different path in the file_put_contents function.

Leave a Comment