Skip to content

Instantly share code, notes, and snippets.

@bj4rtmar
Last active March 4, 2016 10:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bj4rtmar/19c367486d2da5b5f1b9 to your computer and use it in GitHub Desktop.
Save bj4rtmar/19c367486d2da5b5f1b9 to your computer and use it in GitHub Desktop.
Converts text file, with a php array of file extensions to mimetypes, to JSON
use strict;
use warnings;
use JSON;
use Getopt::Long;
my %options;
GetOptions(\%options,
'help',
'reverse|r', # Mimetype to list of extensions. Default is to print Extensions to list of Mimetypes
) or die $!;
if ($options{'help'}) {
print "$_" while <DATA>;
exit 0;
}
my $mime_href = { };
while (my $line = <>) {
next unless $line =~ /^'/;
my ($ext,$tail) = $line =~ /^'(.+?)'.*=> array\((.+)\),?.*\n/;
next unless $ext and $tail;
#example:
#$ext = `zip'
#$tail = `'application/x-compressed', 'application/x-zip-compressed', 'application/zip', 'multipart/x-zip''
if ($options{'reverse'}) {
my %mimes = map { s/'//g; $_ => 1 } split(/,\s?/,$tail);
foreach my $mime (keys %mimes) {
push (@{$mime_href->{$mime}},$ext);
}
}
else {
$mime_href->{$ext} = [ map { s/'//g; $_ } split(/,\s?/,$tail) ];
}
}
print encode_json($mime_href);
__DATA__
Converts the file 'https://gist.githubusercontent.com/nimasdj/801b0b1a50112ea6a997/raw/546891b981020822130ca82ddd107dad8b603d7d/MimeTypes.php' to json
usage: perl phpmime_to_json.pl [options] <file>
options:
--reverse, -r: Mime types to extensions instead of the default (extensions to list of mime types)
--help, -h
example:
Fetch the input file:
$ wget 'https://gist.githubusercontent.com/nimasdj/801b0b1a50112ea6a997/raw/546891b981020822130ca82ddd107dad8b603d7d/MimeTypes.php' -O input.txt
then convert input to json:
$ perl phpmime_to_json.pl input.txt > output.json
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment