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:

1
2
3
4
5
6
7
8
9
10
$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).

PHP: Removing an item from an array

If you have a php array, but need to nuke an item from it, the unset function is just the tool to do that. When iterating through the array after removing the item, you should be slightly careful.

The unset function does remove the item, but it doesn’t “reindex” the array, so you should traverse the array by index-numbers after removing the item. The issue is probably best illustrated by this example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$myArray = Array('item 1', 'item 2', 'item 3');
 
// remove item
var_dump($myArray);
 
unset($myArray[1]);
var_dump($myArray);
 
// Failing bad loop
for ($loop = 0; $loop < count($myArray); $loop++) {
        echo $myArray[$loop] . "\\n";
}
 
// Good loop
foreach ($myArray as $item) {
        echo $item . "\\n";
}

You can dowload the above example code here.