Archive for March, 2010

Export to CSV, PHP class

Thursday, March 25th, 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

Saturday, March 20th, 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

Thursday, March 4th, 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

Tuesday, March 2nd, 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 ]


WordPress