New Zealand repeaters are up! and an intro to csv importing with fgetcsv()

This week, the New Zealand amateur radios on vhf.nz were added to the worldwide Hearham.com repeater listing. These are pulled in with permission and this now allows offline listing of the ham radio repeaters to work for folks in the Android or Linux version of Repeater-START (Showing The Amateur-radio Repeaters Tool):

The map they provide is in Google maps KMZ and the more usable one for programmers, .csv.

Reading CSV

Now at first look the repeater data they give, as any other .csv file, seems pretty simple, reading csv is just explode and read array for each line, right?

$values = explode(',', $row);
var_dump($values);

Well, not so fast – there are some more complex issues with csv – csv can have comma separated values but also “,”s in the cells, which spreadsheets will generally output with standard quotes around. So how do you read this from your webservice?

Thankfully there is a specific function for this you can use to read csv file input, fgetcsv(). The default arguments are what most csv files will be, so for most cases you would just use

while( ($csvrow = fgetcsv($input)) !== FALSE ) {
    //Check count($csvrow) and do what you need to do with expected values

Now one thing you may remember is that the files resource can be a path OR a url (or other things as linked in the documentation. So in this case I directly call up that url with fopen($url), noting that the trusted $url is not something from user input! You wouldn’t want any old internet user to get your app to show a page with data based on fopen(‘file://etc/passwd’) or other system files!

Combine this with a quick check to not try and process the very first line, the table columns, and I had something like this I use to get their listing data:

<?php
$first = TRUE;
$in = fopen('https://vhf.nz/maps/licences.csv','r');
if( $in !== FALSE )
{
	while( ($csv = fgetcsv($in)) !== FALSE )
	{
		if( $first )
		{
			$first = FALSE;
			continue;
		}
		if( count($csv) === 18 )
		{
			var_dump($csv); // Do all you need to with $csv[0], $csv[1], $csv[2] cells...
		}
	}
}

You can see the result imported into various branch listings in the directory, or filter all near a certain location, or browse the results in the app.

Leave a Reply

Your email address will not be published. Required fields are marked *

two × = twelve