...

View Full Version : How do I "read" data in a csv file using PHP?



Chris55
02-17-2012, 02:55 PM
How would I go about setting up a PHP script to link to a image link contained in a csv file? Basically I have set up a Javascript carosel displaying product images. The difficulty i am having is i want it to only display published content as the products change frequently. How would a set up a php script to read my .csv file and link to an image on my sever only if the published tab says yes? Sorry if i havn't explained this very well but any help would be much appriciated.

Rowsdower!
02-17-2012, 03:32 PM
This has nothing at all to do with HTML/CSS fixes, but here you go...

To parse a CSV file in PHP you first need to open and read the file contents. Then you go line-by-line and pull the data into an array that you can use to run your intended process. Overall it looks something like this:


$csv_file_path = "path/to/file.csv";
if(is_file($csv_file_path)){
$my_csv_array=array();
$file = fopen($csv_file_path, 'r');
while(($line = fgetcsv($file)) !== FALSE){
//each loop gives us a variable $line which is an array of the csv elements in the current row. So we push the row into the csv array...
array_push($my_csv_array,$line);
}
fclose($file);

//now we take a look at what is inside to make sure we have what we expected:
print_r($my_csv_array);

//and then we go on to do whatever it is we want to do with this information
print "<p>This is where we would do something worthwhile after having deleted the print_r() bit just above this part.</p>";
}
else{
print "<h1>CSV FILE NOT FOUND.</h1>\n";
}

teedoff
02-17-2012, 03:56 PM
Wouldn't it be easier to maintain in a MySQL database though? The code would virtually work the same way, but maintainence would be a lot easier.

Rowsdower!
02-17-2012, 08:30 PM
Wouldn't it be easier to maintain in a MySQL database though? The code would virtually work the same way, but maintainence would be a lot easier.

Absolutely, for web use. OP might have a strong need to use a desktop application to manage things locally, though, and then upload to the server (or any number of other possibilities for why they might prefer csv data). You never know!

alykins
02-17-2012, 09:38 PM
&& (just to add :) ) some programs only allow to save off as csv files (*thinking in particular a lot of network traffic analysis tools that I've used in the past for packet capturing)

teedoff
02-18-2012, 12:53 AM
Absolutely, for web use. OP might have a strong need to use a desktop application to manage things locally, though, and then upload to the server (or any number of other possibilities for why they might prefer csv data). You never know!

lol you are correct. I just always think in terms of dynamic page content..lol



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum