For my old link scraping project, I had to figure out a neat way to read CSV files and present the data on the page. There's a few choices in PHP for this; I went with the explode method, which has some limitations, mainly that it can't escape characters. So if you have a CSV file that has a line like
1;2;3;4;4;4;5;6
and the 4's are supposed to be one field, you would adapt your file to look like
1;2;3;4\;4\;4\;4;5;6
to tell some script to ignore those semicolons, but explode requires some jiggery-pokery to get it to do that. Could this be more easily done with fgetcsv? Doubtlessly so, but I couldn't figure it out in under ten minutes so I went with what I know.
The bit of PHP below reads a CSV separated by semicolons (an SSV?) and ignores any semicolons preceded by a backslash, after which you can build any page you want with the fields, in any order you want. It also includes a little extra thing you can use or discard: shortanimal, which takes whatever field you select and shortens it, in this case to 3 characters.
The semicolon-within-a-field issue is resolved by reading the file and then replacing each escaped semicolon (so \;) with '53m1k010n', a phrase you're unlikely to encounter in any CSV file but you can use any phrase, of course. Then it explodes the CSV file into its separate fields, at which point the semicolons are added back in. Hokey, but it works fine.
So let's say you have a file, csv.csv, that looks like this:
the fish;sea;swim the monkeys;trees;swing the horses;hills;gallop (though they also poop\; more on that later)
foreach ($site as $site):
echo '',$site['shortanimal'],'. ',$site['act'],' in the ',$site['place'],'. which animal am i talking about?<br>why, it\'s ',$site['animal'],!'<p>
';
endforeach;
?>
</body>
</html>
That page will look like this:
the ... swim in the sea. which animal am i talking about? why, it's the fish!
the ... swing in the trees. which animal am i talking about? why, it's the monkeys!
the ... gallop (though they also poop; more on that later) in the hills. which animal am i talking about? why, it's the horses!
download csvread.zip1.7 kB, includes example page, csv file and this page as a README
I publish this little PHP snippet into the public domain, so you can do whatever you want with it, no questions asked - though I'm always available for linkbacks, of course.