Loading data from a file with PHP

In programming languages common tasks should be easy, and surprisingly often I find my self loading data from some source file into a database. With PHP loading a CSV file into the database - or posting the data to an API - is quite easy.

The only trick is to know the functions file_get_contents, split (and possibly list).

The routine goes something like this:

$fileName = 'rawData.csv';

$content = file_get_contents($fileName);
$rows = split("\n", $content );

foreach ($rows as $row) {
	list($item1, $item2, item3) = split(';', $row);

	// Do something interesting...
}

The script gets the contents of file into a variable ($contents). Split the contents into an array ($rows) and the forach loop across each row. The first line of the loop splits the row into three fictitious items and the rest of the loop could do something interesting to the data read from the file.

I usually run scripts like these from the command-line (yes, you can do that with PHP scripts).