Splat

splat.php is a simple PHP utility that will run another script with each row of a CSV as input arguments. It was developed internally for one of our projects and we're open-sourcing it for the benefit of the community (not that it's all that much, but hey, code is code!)

Say you have a CSV file like this:

arg1name, arg2name, arg3name, arg4name
arg1    , arg2    , arg3    , arg4
arg1a   , arg2a   , arg3a   , arg4a
myarg1  , myarg2  , myarg3  , myarg4

Now, say you need to run the following commands:

script.php arg1 arg2 arg3 arg4
script.php arg1a arg2a arg3a arg4a
script.php myarg1 myarg2 myarg3 myarg4

That's exactly where splat.php comes in! It's an extremely simple PHP utility that calls another program (which may or may not also be a PHP script) for each row of a CSV file, with each column automatically expanded to an argument to that script. Thus, providing splat.php with another script and a 4-column CSV as inputs means that the other script gets called with 4 arguments and as many times as there are rows in the CSV.

Usage (where script.php is the script you want to call for each row of values.csv) — php splat.php script.php values.csv

Here is splat.php in its entirety:

<?php
// Developed by InterLinked 2020. https://interlinked.us/pages/splat
// Feel free to reuse or redistribute. Attribution appreciated. No warranty of any kind is provided with this program, but you may let us know if there are issues
if (sizeOf($argv) !== 3) {
	die("Args: " . sizeof($argv) . " Usage: php splat.php script.php values.csv\n");
}
$file = $argv[2];
if (($handle = fopen($file, 'r')) !== FALSE) { // necessary if a large csv file
	$info = array();
	$d = 0;
	while (($data = fgetcsv($handle, 1000, ',')) !== FALSE) {
		if ($d > 0) { # skip CSV file head
			$info[] = $data;
		}
		$d++;
	}
	fclose($handle);
	$d--; # head didn't count
	foreach ($info as $data) {
		system("php $argv[1] \"" . implode('" "', $data) . "\"");
		$d--;
		echo "\n";
		echo $data[0] . "\n";
		echo " $d left\n";
		if ($d >= 1) {
			sleep(4); # if you need a delay between each iteration of script.php, do this here; otherwise, remove this
		}
	}
	echo "Done\n";
}
?>