PHP Script to Convert all line-endings from Windows to Unix

This PHP script will normalize line-endings in all files in a directory, by converting all line endings from Windows format to Unix format. That is, it will convert any \r\n or \r line breaks to \n. This will run on all “.txt” files in the directory where you place this file, but you can change that on line 10.

HTML and PHP

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Normalize Line Endings</title>
</head>
<body>
<h1>Convert all line-endings from Windows to Unix</h1>
<?php
$pattern = __DIR__ ."/*.txt";
$files = glob($pattern);

// Can do multiple file types like this:
//$files = glob('folder/*.{php,txt}', GLOB_BRACE);

foreach($files as $file) {
    isa_normalize($file);
}

function isa_normalize ($filename) {
        echo "Convert the ending-lines of $filename... ";

        $string = @file_get_contents($filename);

        if (!$string) {
            echo "Could not convert the ending-lines : could not load the file.";
            return false;
        }

        //Convert all line-endings from Windows to Unix
        $string = str_replace("\r\n", "\n", $string);
        $string = str_replace("\r", "\n", $string);
        file_put_contents($filename, $string);

        echo "Ending-lines converted.";
        return true;
    }
?>
</body>
</html>

By

Questions and Comments are Welcome

Your email address will not be published. All comments will be moderated.

Please wrap code in "code" bracket tags like this:

[code]

YOUR CODE HERE 

[/code]