Last active
February 2, 2021 23:13
-
-
Save neitanod/7ad4bd57fb7e68e5856c93f31cd66b3a to your computer and use it in GitHub Desktop.
Command line script to run forceutf8 function directly from bash
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env php | |
<?php | |
require_once("Encoding.php"); // Specify correct path to library here. | |
if(empty($argv[1])) { | |
while($f = fgets(STDIN)){ | |
echo ForceUTF8\Encoding::toUTF8($f); | |
} | |
} else { | |
if(!file_exists($argv[1])){ | |
if ($argv[1] != "--help") { | |
fwrite(STDERR, "File not found. Use --help for help.\n"); | |
exit(1); | |
} | |
echo("Specifiy the file to convert or pipe some text.\n\n"); | |
echo("Example 1:\n ls | forceutf8\n\n"); | |
echo("Example 2:\n forceutf8 input_file.txt # will output converted text\n\n"); | |
echo("Example 3:\n forceutf8 input_file.txt replace # will replace file contents\n\n"); | |
die(); | |
} else if(!is_file($argv[1])) { | |
echo($argv[1]." is a directory.\n"); | |
exit(2); | |
} 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); | |
if(!empty($output_filename)) { | |
unlink($filename); | |
rename($output_filename, $filename); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment