Read data from a CSV

Hi Guys!

Im trying to read a CSV file using PHP and output the data. When I upload the CSV, it only outputs the first line of data. Any idea why this may happen?

Here’s the code I am using:


$file_handle = fopen($_FILES['csv']['tmp_name'], "r");
			while(!feof($file_handle)) {
				$data = fgetcsv($file_handle, 10240);
				
				$domain = $data[0];					
				$price = $data[1];
				$currency = $data[2];
				
				
				echo $domain."<br />";
}

Here’s the CSV I am using:

a-mortgage.com,4000,USD
a-one.com,3000,USD
a-online-pharmacy.com,2500,USD
a-perfect-world.com,600,USD
a-photo.com,1600,USD
a-plan.net,1300,USD
a-property.com,3000,USD
a-room.com,3500,USD
a-run-for-your-money.com,500,USD

You are only getting the first line of data.

"fgetcsv() returns NULL if an invalid handle is supplied or FALSE on other errors, including end of file."

So, instead of:

while(!feof($file_handle)) { …

use:

while ($data = fgetcsv($file_handle, 10240)) { …

Suggestion…

  1. save the file (ie my_data.csv)

then…


/* open file into an array */
$lines = file("my_data.csv");

/* loop through the array and explode each ine */
for($i=0;$i<count($lines);$i++) {
  $line_array = explode(",", $lines[$i]);
  /* do whatever with the info - here we will simplye display it */
  echo $line_array[0] . "<br/>";
  echo $line_array[1]; . "<br/>";
  echo $line_array[2]; . "<br/>";
  echo "<hr>";
}