This is a totally experimental question, but if answered it will save me hours of manual HTML mark up.
In theory it should work, but can appreciate advice if I’m talking rubbish.
I need a loop to pull column data from columns in a CSV spreadsheet, and echo them in HTML mark up.
I can’t write PHP but this is how I envisage the loop work…
<?php
// here it needs to load the CSV file and get the column data and output them as variables (I guess)
echo <div id="interactive-map">
// here a loop needs to begin to output this line off HTML...
// with the arrayed variables...
<div id="[varible-1]" class="[varible-2]" title="[varible-3]"><span>[varible-3]</span></div>
// loop finished once no more rows left in CSV
echo </div>
?>
So the result should look like this…
<div id="interactive-map">
<div id="1" class="free" title="Uber"><span>Uber</span></div>
<div id="2" class="free" title="Howdy"><span>Howdy</span></div>
<div id="3" class="free" title="Love"><span>Love</span></div>
<div id="4" class="free" title="Gimme"><span>Gimme</span></div>
<div id="5" class="free" title="Totally"><span>Totally</span></div>
<div id="6" class="free" title="Spank"><span>Spank</span></div>
</div>
The CSV files looks like this…

(source: motocom.co.uk)
Any help or advice would be TRULY amazing! Thanks
// UPDATE BELOW FOLLOWING FIRST ANSWER
My CSV below viewed as text…
id,class,name
1,free,Uber
2,free,Howdy
3,free,Love
4,free,Gimme
5,free,Totally
6,free,Spank
The PHP below…
<?php
$file = fopen('file.csv', 'r');
$fields = array();
if ($file) {
while (($data = fgetcsv($file)) !== false) {
if(empty($fields)) {
$fields = $data;
continue;
}
$row = array_combine($fields, $data);
$output = sprintf("% is ID, % is CLASS, % is NAME",
$row['id'],
$row['class'],
$row['name']);
echo $output;
}
fclose($file);
}
?>
It’s not quite working properly, what am I doing wrong?
With regards to adding the HTML, I put the mark up inside where the echoed text is and it gets confused :-/
It is echoing stuff but not the desired info from the csv.
To read the file, the easiest is to use the built-in
fgetcsvin a loop. You can cook up your own parsing code, but it’s really thankless work to make it behave correctly in the presence of field delimiters and escaped characters.After reading the names of the CSV fields (first iteration) and their values for each row (subsequent iterations), you can use
sprintforvsprintfto easily construct an HTML string to output.For example:
See it in action.