Posts Tagged ‘PHP’

Converting any number to a Currency (or 2 decimal places)

May 29th, 2009

Yes it sounds fairly elementary doesn’t it… yet I can’t find a PHP function to just do it?

If, like me, you store your currency values in your database as integers (don’t ask why, I just do) then you need to multiply by 100 on the way in and divide by 100 on the way out.

The obvious problem (or maybe not so obvious) is that when multiplying a number 100.1 is different to 100.10 and therefore the former needs to be converted to 100.10 for the resultant number to be correct.

The following function simply does that whilst checking for the occurence of a decimal place and concatenating .00 in that situation.

function convert_to_currency($num) {
    if (strpos($num, '.') == false) {
        $num = $num . '.00';
    } else {
        $num = sprintf("%01.2f", (float)$num);
    }
    return $num;
}

This should reliably format the number ready to be manipulated for either a database or to be directly output.

Turning an Array or Object into XML using PHP

March 25th, 2009

I have read a fair few tutorials written by others using classes and DOM functions to create XML from arrays. But what happens if you have an older PHP installation or prefer to keep things really simple as I do.

The following function declarations generate an XML string from an associative array. In my scripts that use it, it’s usually coupled with a download function so that XML is generated on the fly and then downloaded to a file. The main advantage of this is that you can write a basic import script using the SimpleXML library to restore the array at any time which makes it perfect for use as part of a backup/restore system.

Wordpress stores alot of it’s sitewide data in a table called wp_options which stores a named key and a value string for each piece of information. Plugins can also use this table by using the add_option, update_option, delete_option and get_option functions passing values, arrays or objects along with a key name. This isn’t an ideal data structure but does mean that plugin writers can easily store information without bloating the database with unnecessary and often badly designed tables.

The Code..

function generate_xml_from_array($array, $node_name) {
	$xml = '';

	if (is_array($array) || is_object($array)) {
		foreach ($array as $key=>$value) {
			if (is_numeric($key)) {
				$key = $node_name;
			}

			$xml .= '<' . $key . '>' . "\n" . generate_xml_from_array($value, $node_name) . '</' . $key . '>' . "\n";
		}
	} else {
		$xml = htmlspecialchars($array, ENT_QUOTES) . "\n";
	}

	return $xml;
}

function generate_valid_xml_from_array($array, $node_block='nodes', $node_name='node') {
	$xml = '<?xml version="1.0" encoding="UTF-8" ?>' . "\n";

	$xml .= '<' . $node_block . '>' . "\n";
	$xml .= generate_xml_from_array($array, $node_name);
	$xml .= '</' . $node_block . '>' . "\n";

	return $xml;
}

Usage

You can use the above functions by generating an array or object as normal and then using the following code. The function returns the XML and you can then do with it as you wish.

$xml = generate_valid_xml_from_array($array);

Things to consider

XML doesn’t allow for numeric tags so any numbers are replaced by the content of the $node_name variable. XML also doesn’t allow for certain special characters within it’s tags and ,for this reason, the htmlspecialchars function is passed over the raw data before it is placed into the string.

You can, however make use of cdata tags which tells XML readers to essentially ‘ignore whats coming next’. See the w3schools explanation of cdata here: http://www.w3schools.com/XML/xml_cdata.asp. There is no right or wrong way to escape data but if you have problems with my script then factor in the cdata tags replacing the htmlspecialchars call and see how you get on.

Alternatively feel free to contact me by commenting on this post or using the contact form and I will work with you to get your script working.

XLS Download from PHP Class!

January 21st, 2009

Following on from my last post on creating a proper XLS spreadsheet from PHP I have just written a small class which will do all the hard work for you if necessary.

It will handle rows and columns automatically aswell as being able to be passed an array and then generating a spreadsheet download for you.

Download: XLS from PHP Example Class (783 bytes)

Sample usage is as follows:

	//Require the file
	require_once (SHARED_CLASSES_DIR . 'xls.class.php');

	//Instantiate the class.
	$xls = new xls(); 

	//Just build an example array out of test data
	$array = array(
		array(1,2,3,4,'five')
		, array('five','test' ,4,3, 0)
	);

	//Triggers the download using the passed array
	$xls->download_from_array($array);

Note that when instantiating the class you can pass a string as an argument and it will set the name of the XLS download. No need to add .xls to the end because it will do that for you.

Download: XLS from PHP Example Class (783 bytes)

Creating a Downloadable Spreadsheet from PHP

January 16th, 2009

I have written several systems that show data on a page but also provide a CSV download file either through a textarea with formatted data inside to copy and paste or via a download link and creates a file on the fly.

I recently decided that this wasn’t the best way to do it seeing as the people will want to be using Microsoft Excel to view the data. It is possible to write a spreadsheet using PHP and using an example from AppServ I started to do it this way.

The original link is included above but here is my simplified version with smaller more understandable function naming:

Download the example script here: XLS from PHP Example (723 bytes)

<?php

function xls_BOF() {
	echo pack("ssssss", 0x809, 0x8, 0x0, 0x10, 0x0, 0x0);
}

function xls_EOF() {
	echo pack("ss", 0x0A, 0x00);
}

function xls_write_cell($row, $col, $value='') {
	if (is_numeric($value)) {
		echo pack("sssss", 0x203, 14, $row, $col, 0x0);
		$value = pack("d", $value);
	} else {
		$l = strlen($value);
		echo pack("ssssss", 0x204, 8 + $l, $row, $col, 0x0, $l);
	}

	echo $value;
}

// Send Headers to set the Filename and force a download of the contents of the script
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");

 // Put the filename in \"'s if you want it to include spaces
header("Content-Disposition: attachment;filename=" . $filename . ".xls");
header("Content-Transfer-Encoding: binary ");

xlsBOF(); //Start the Spreadsheet

xls_write_cell(0, 1, 'Column 1');
xls_write_cell(0, 2, 'Column 2');
xls_write_cell(0, 3, 'Column 3');

$row = 1;
for ($i=0; $i<2; $i++) {
	xls_write_cell($row, 0, 'Row ' . $row . ' Column ' . $i);
	xls_write_cell($row, 1, 'Row ' . $row . ' Column ' . $i);
	xls_write_cell($row, 2, 'Row ' . $row . ' Column ' . $i);

	$row++;
}

xlsEOF(); //End the Spreadsheet

exit(); //Exit the script after download

?>