I have an issue with exporting BLOB to a csv file using php. Obviously blob is not a normal field, but it is on occasion used. But here’s what I need, I need this script to work by taking a table array and export each row in csv format. Blob is screwing this up. I’ve tried to base64_encode the blob, but I believe that would export the blob incorrectly.
Here is what I have so far:
function exportcsv($tables) {
foreach ($tables as $k => $v) {
$fh = fopen('sql/'.$v.'.csv', 'w');
$sql = mysql_query("SELECT * FROM $v");
while ($row = mysql_fetch_row($sql)) {
$line = array();
foreach ($row as $key => $v) {
$line[] = base64_encode($v);
}
fputcsv($fh, $line, chr(9)); //tab delimiting
}
fclose($fh);
}
}
Any help would be appreciated.
EDIT: Here is an image of the blob export WITHOUT base64_encode().
https://www.strongspace.com/shared/crypok1lxb
So, will base64 protect the format of blob when the need to reimport arises?
The purpose of Base64 encoding is to make binary data survive transport through transport layers that are not 8-bit clean, so yes, you are on the right track with this.
What you really need to be worried about is that fputcsv() function. What are the dangerous items you need to check for?
According to this link, Base 64 encoding only spans A-Z, a-z, 0-9, + and /, which means you are safe and the new line in the image you posted is probably an artifact from word wrapping in the IDE you are using. Now all that you have to remember is that when you want to import this data back into the DB, don’t expect to just use mysqldump or mysql < to pipe it in. You’re going to have to create another php function that uses base64_decode to get the data back into it’s original state.
You should also be aware that you are currently encoding all of the fields, not just the blob data. Base64 encoding takes up some ~33% more space as an FYI so you may want to define your tables with some bit indicating if the field is a blod and you want to enable B64 encoding on it.