Last active
August 29, 2015 14:20
-
-
Save PurpleBooth/f1c33cc83ab0dd4eaacc to your computer and use it in GitHub Desktop.
This file contains 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
<?php | |
if(count($argv) != 2) { | |
echo "Attempt to recursively convert a directory of XML files to UTF-8 and Fix any unescaped & symbols\n"; | |
echo "Usage {$argv[0]} directory\n"; | |
exit(1); | |
} | |
$path = realpath($argv[1]); | |
$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST); | |
foreach($objects as $name => $object){ | |
if(mb_strtolower($object->getExtension()) == 'xml') { | |
$contents = file_get_contents($object->getRealPath()); | |
$encoding = mb_detect_encoding($contents); | |
if(!$encoding) { | |
$encoding = 'Unknown'; | |
} | |
echo "{$name}: Probably ". $encoding . " converting to UTF-8\n"; | |
$decoded = mb_convert_encoding($contents, 'UTF-8'); | |
$regex = "/(?!<\\!\\[CDATA\\[)(?:&([^;\\W]*([^;\\w]|$)))(?!\\]\\]>)/"; | |
$replacement = "&$1"; | |
$decoded = preg_replace($regex, $replacement, $decoded); | |
file_put_contents($object->getRealPath(), $decoded); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment