Skip to content

Instantly share code, notes, and snippets.

@neitanod
Created February 1, 2019 17:24
Show Gist options
  • Save neitanod/a5eff5bc5b7b49449ea4c952e2a02d28 to your computer and use it in GitHub Desktop.
Save neitanod/a5eff5bc5b7b49449ea4c952e2a02d28 to your computer and use it in GitHub Desktop.
#!/usr/bin/env php
<?php
/**
Usage:
ls | forceutf8 # send input via stdin
forceutf8 file.txt # output converted file.txt
forceutf8 file.txt replace # do not output contents, replace instead (caution!)
for file in `find .`;do;forceutf8 "$file" replace;done # process current folder recursively (Linux)
for file in ./*;do;forceutf8 "$file" replace;done # process current folder non-recursively (Linux)
*/
require_once("Encoding.php");
if(empty($argv[1])) {
while($f = fgets(STDIN)){
echo ForceUTF8\Encoding::toUTF8($f);
}
} else {
if(!file_exists($argv[1])){
echo("Specifiy the file to convert or pipe some text.\n");
die();
} else if(!is_file($argv[1])) {
echo($argv[1]." is a directory.\n");
die();
} else {
$filename = $argv[1];
echo($filename."\n");
$file = fopen($filename, "r");
$output = null;
if(!empty($argv[2]) && $argv[2] == "replace") {
$output_filename = $argv[1].".forceutf8";
$output = fopen($output_filename, "w");
}
while($f = fgets($file)){
if(!is_null($output)) {
fputs($output, ForceUTF8\Encoding::toUTF8($f));
} else {
echo ForceUTF8\Encoding::toUTF8($f);
}
}
fclose($file);
if(!is_null($output)) fclose($output);
unlink($filename);
rename($output_filename, $filename);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment