Export to CSV, PHP class

25th March, 2010

Whilst working on a project I had to set up the ability to export information in spreadsheet format. I looked around at the various existing options but they all seemed over complicated and bloated for what I needed so I ended up writing my own class to do it.

Here’s what I came up with:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
<?php
/**
 * @author  : Jim Hollington
 * @date    : 2010-03-24
 * @desc    : A simple class that takes 2 arrays and outputs a CSV file
 * @version : v0.1
 * @license : GPL
 */
class CSV {
 
	/**
	 * @param array: optional - Column headings
	 * @param array: optional - Content to go in CSV
	 * @param string: optional - File name to save CSV as
	 *
	 * @return object: CSV object
	 **/
	public function __construct($columns=null,$data=null,$file_name=null)
	{
		// if all required data has been passed to constructor then make csv immediately
		if( $columns && $data && $file_name )
		{
			$csv = $this->build($columns,$data);
			$this->save($csv,$file_name);
		}
	}
 
	/**
	 * @param array: Column headings
	 * @param array: Content to go in CSV
	 *
	 * @return string: CSV format string from input
	 **/
	public function build($columns, $data)
	{
		$csv = ''; // initialise csv variable
 
		foreach($columns as $heading) // csv column headings
		{
			$csv .= $heading.','; // concat heading onto row
		}
		$csv .= "\n"; // all the headings have been added so move to new line for csv content
 
		foreach($data as $row) // csv table content
		{
			foreach($columns as $column => $t)
			{
				if(strpos($row[$column],',')) // if cell content has a comma in it...
				{
					// ...double any existing quotes to escape them...
					$row[$column] = str_replace('"','""',$row[$column]);
					// ...and wrap the cell in quotes so the comma doesn't break everything.
					$row[$column] = '"'.$row[$column].'"';
				}
				$csv .= $row[$column].","; // concat the value onto the row
				if($t==end($columns))
				{
					// if we're at the end of a row move to a new line for next row
					$csv .= "\n"; 
				}
			}
		}
		return $csv;
	}
 
	/**
	 * @param string: String in CSV format
	 * @param string: optional - File name to save CSV as
	 *
	 * @return void
	 **/
	public function save($csv,$file_name=null)
	{
		// if no file name is provided set the file name to todays date
		if(!is_null($file_name)) $file_name = date('Y-m-d');
		// set content type and file name then output csv content
		header("Content-type: application/octet-stream");
		header("Content-Disposition: attachment; filename=\"$file_name.csv\"");
		echo $csv;
	}
}
 
?>

Usage:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<?php
// this array is used to set the column headings, 
// the array keys are used to match the columns to the corresponding row values.
$columns = array(
	'col1' => 'Column 1',
	'col2' => 'Column 2',
	'col3' => 'Column 3'
);
// this array will be the actual content of the table.
$data = array(
	0 => array(
		'col1' => 'Row 1',
		'col2' => 'Row 1',
		'col3' => 'Row 1'
	),
	1 => array(
		'col1' => 'Row 2',
		'col2' => 'Row 2',
		'col3' => 'Row 2'
	),
	2 => array(
		'col1' => 'Row 3',
		'col2' => 'Row 3',
		'col3' => 'Row 3'
	),
);
// this will put the above information into a csv sheet and offer to save as 'test.csv'.
new CSV($columns, $data, 'test');
 
//alternatively you could put the csv content into a variable as a string...
$csv = new CSV();
$csv_string = $csv->build($columns, $data);
// then to save...
$csv->save($csv_string);
?>

Class outputs:

Column 1,Column 2,Column 3,
Row 1,Row 1,Row 1,
Row 2,Row 2,Row 2,
Row 3,Row 3,Row 3,

BIMM Gig Photographs

20th March, 2010

I did a little bit of freelance photography for BIMM (Brighton Institute of Modern Music) last night; photographing one of their many gig nights. Never done any photography like it before but I certainly wouldn’t mind doing it again.

Check out the whole set here: http://www.flickr.com/photos/oddvalue/sets/72157623534152247/

PHP debugging

4th March, 2010

After having some issues with a PHP script I decided to try and make a debug script that would make it easier to work out where things were going wrong.
This is the code I ended up with:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<?php 
/**
 * @param mixed $var
 * @param boolean $visible
 * @param boolean $return
 * @return mixed
 */
function dump(&$var, $visible = true, $return = false)
{
	$location = debug_backtrace();
 
	if($visible)
	{
		$open = '<pre>';
		$close = '</pre >';
	}
	else
	{
		$open = "\n<!--\n";
		$close = "\n-->\n";
	}
 
	$message = "Dump from '" . $location[0]['file'] . "' on line: " . $location[0]['line'] . "\n";
 
	$r = var_export($var, true);
 
	$r = $open . $message . $r . $close;
 
	if ($return) return $r;
	echo $r;
}
?>

It outputs in a format like this:

Dump from 'C:\wamp\www\index.php' on line: 19
array (
  0 => 'value'
)

It works pretty well but even with this functionality I still found myself wanting more so I did a bit of google searching and found Gosu.pl PHP debug tools. I didn’t even know something like this could exists, its so useful.
Seriously worth checking out.

PHP Form Builder and Validator Class

2nd March, 2010

I’ve been working with some long forms recently and started getting really bored of typing out the full form syntax each time so I decided to write a class that could help the process along a bit.

It has the option for text inputs, textareas, drop downs, a date drop down, hidden inputs and validation rules.

It’s still a little rough round the edges but I plan to extend it to support more input types.

Check out the source and demo below:

[ demo ]

Demo Source:

[ index.php ][ form_array.php ][ form_builder.php ]

Macro!

17th February, 2010

IMGP0310, originally uploaded by oddvalue.

Dicking around with a bag of eyelets and a macro tube attachment for my camera. It’s not great seeing as my lens doesn’t have manual aperture control but hey… a tiny tripod and a 15 second exposure sorted that.

A Valentine’s Day trip to Highgate Cemetery

16th February, 2010
I started a four week internship last week so I haven’t had much time to work on my own stuff.  On the plus side this internship has been doing wonders for my coding ability.
Anyway, on to the subject of this post… I somehow ended up going to Highgate Cemetery last Sunday (Valentine’s Day) and although it was a bit of a random choice of activity it was very enjoyable, if not a bit cold.
Luckily I had my new Pentax K-x with me so I took it out for a spin. It was the first time I’d properly used it since getting it and now I’m itching to use it again. Not sure what to photograph though.
Anywho – click the link for some of the better photos: http://www.flickr.com/photos/oddvalue/sets/72157623318333883/

IMGP0266

Pure CSS 3 Analogue Clock

4th February, 2010

Ok so I haven’t posted anything here in ages. The forum thing never really happened because I got sidetracked upgrading my own site. I did make a pretty good start on it so maybe I’ll finish it one day, just not now.

…but enough of what I’m not doing… I’ve been looking at HTML5 and CSS3 recently and I’m really liking what I’m seeing. It’s just a shame that its going to be some time until it’s actually commercially usable.

Go here and help retire the lame evil that is IE6 http://petitions.number10.gov.uk/ie6upgrade/

Anyway, I’ve been experimenting with CSS 3 and I cannot wait till all the main browsers have full support for it. I found this demo here http://www.fofronline.com/experiments/clock/#clock for a CSS3 analogue clock and decided to try make my own.

Here it is:

It’s an analogue clock that is created using nothing but CSS, not even images. There is some JavaScript but that’s only there to to find out what the time is.

Compatible browsers: Google Chrome, Safari 4

[ click here to see clock in action ]

Forum Design

22nd October, 2009

forum designI’ve been reading up on the CodeIgniter framework and I decided that rather than just following basic tutorials I would try and make something.

I will be attempting to make a basic forum, I had planned on starting today… I got a bit sidetracked doing a mock-up design for it. It’s the first time I’ve properly tried to design anything in a while so I got quite in to it.

I think the design has come out alright. Will make a start on making it into a functional forum soon.

I’m going to the fullfrontal javascript conference

12th October, 2009

fullfrontal

 

I just bought my ticket to go to fullfrontal 2009. This will be the first time I’ve done anything like it and I’m quite looking forward to it.

I need to get more in to JavaScript and hopefully this will be a good starting point for that.

Papervision3D

7th October, 2009
Get Adobe Flash player


After years of intending to learn a bit about the Papervision 3D engine I have finally dipped my toe in. I made the model in Maya based on a Cubeecraft design – http://www.cubeecraft.com/cubee/master-shake

There is a bit of distortion in the texture so it’s no perfect… but it’s a start.


WordPress