Created
January 10, 2017 19:13
-
-
Save goreilly/ffe6078eabe61acd12664b6d09b68aff to your computer and use it in GitHub Desktop.
Generate Data Interchange Format from key value array source
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 | |
$data = [ | |
[ | |
'hello' => 'world', | |
'world' => 'hello', | |
], | |
[ | |
'hello' => '12387293871293847123894712342134', | |
'world' => '12387293871293847123894712342134', | |
], | |
[ | |
'hello' => '12387293871293847123894712342134', | |
'world' => 'zxcv', | |
], | |
]; | |
function make_dif($key_value_pairs) | |
{ | |
$size = 0; | |
$output = tmpfile(); | |
$write = function (...$values) use ($output, &$size) { | |
foreach ($values as $value) { | |
$size += fwrite($output, $value . "\r\n"); | |
} | |
}; | |
$write_row = function ($row) use ($write) { | |
$write('-1,0', 'BOT'); | |
foreach ($row as $value) { | |
$write('1,0', '"' . addcslashes($value, '"') . '"'); | |
} | |
}; | |
$write('TABLE', '0,1', '"PHP"'); | |
$write('VECTORS', "0,0", '""'); | |
$write('TUPLES', "0,0", '""'); | |
$write('DATA', '0,0', '""'); | |
$first = true; | |
foreach ($key_value_pairs as $row) { | |
if ($first) { | |
$write_row(array_keys($row)); | |
$first = false; | |
} | |
$write_row($row); | |
} | |
$write('-1,0', 'EOD'); | |
rewind($output); | |
return [$output, $size]; | |
} | |
ob_start("ob_gzhandler"); | |
list($out, $size)= make_dif($data); | |
header('Content-Type: text/plain; charset=UTF-8'); | |
header("Content-Length: $size"); | |
header('Content-Disposition: attachment; filename="export.dif"'); | |
fpassthru($out); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment