October 19, 2009

Convert a 2D Associative Array To CSV using PHP

Here is a bit of code to convert an array of associative arrays into a CSV file. The first line will be a header line of the key values:

function to_csv( $array ) {
 $csv;

 ## Grab the first element to build the header
 $arr = array_pop( $array );
 $temp = array();
 foreach( $arr as $key => $data ) {
   $temp[] = $key;
 }
 $csv = implode( ',', $temp ) . "\n";

 ## Add the data from the first element
 $csv .= to_csv_line( $arr );

 ## Add the data for the rest
 foreach( $array as $arr ) {   
   $csv .= to_csv_line( $arr );
 }

 return $csv;
}

function to_csv_line( $array ) {
 $temp = array();
 foreach( $array as $elt ) {
   $temp[] = '"' . addslashes( $elt ) . '"';
 }

 $string = implode( ',', $temp ) . "\n";

 return $string;
}
Permalink • Print • Comment

September 1, 2009

Backup and Restore Disk Images Over A Network

Here is a quick and easy way to save and restore hard disk images using dd, netcat and gzip.

To Save An Image:
On the server: nc -l -p 7000 | dd of=Output.img
On the client: dd if=/dev/sdb | gzip -9 | nc 12.34.56.78 7000

To Restore:
On the client: nc -l -p 7000 | gzip -dc | dd of=/dev/sda
On the server: dd if=Output.img | nc 12.34.56.78 7000

I just boot the client using an Ubuntu live-cd, all the neccessary tools are already installed. I store my images gzipped to save space, I just copied a 40 GB disk and the image file compressed down to 4.4 GB!

Permalink • Print • Comment
Made with WordPress and a search engine optimized WordPress theme • Fire Brick skin by Denis de Bernardy