Jump to content

How to Read a CSV File?


Miguel-php

Recommended Posts

Hello,

 

I have just found this forum and it looks like a goldmine of information!  I am hoping someone might have the answer to this;

 

How do you read a CSV file with PHP?

 

For example, if I was selling carpets online, the customer would enter a width and length eg. 39 x 6

 

This would then call on a CSV file which would look like the below;

 

      10 20 30 40 50

5     1  2  3  4  5

10  6  7  8  9  10

 

How would I get the PHP script to return the price of 7?

 

Many thanks!!

 

 

Link to comment
https://forums.phpfreaks.com/topic/139975-how-to-read-a-csv-file/
Share on other sites

Thanks for your reply.  I've had a look at the examples but can't figure out how to get the function go to the correct column and row?

 

Can you elaborate further.

 

How would I get the PHP script to return the price of 7?

 

 

Should read 9 - my mistake!!  ::)

 

Many thanks

To read the file into a nicely structured array:

$carpetFile = fopen('data.csv','r');
$carpetData = array();
$carpetDataKeys = array();
$i = 0;
while (($carpetDataRecord = fgetcsv($carpetFile,1000,',')) !== False) {
if ($i++ == 0) {
	$carpetDataKeys = $carpetDataRecord;
	$discard = array_shift($carpetDataKeys);
} else {
	$iKey = array_shift($carpetDataRecord);
	foreach($carpetDataRecord as $key => $carpetValue) {
		$carpetData[$iKey][$carpetDataKeys[$key]] = $carpetValue;
	}
}
}
fclose($carpetFile);

echo '<pre>';
print_r($carpetData);
echo '</pre>';

 

To retrieve the appropriate value from the array:

$length = 39;
$width = 6;
foreach ($carpetData as $widthKey => $carpetRow) {
if ($widthKey >= $width) {
	foreach ($carpetRow as $lengthKey => $carpetCost) {
		if ($lengthKey >= $length) {
			break 2;
		}
	}
}
}

echo 'Array Value is '.$carpetCost.'<br />';

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.