Reputation: 105
I want to read the csv file column wise and get the every column data into specified array
[country]
Array(
[0]=>Australia
)
[city]
Array(
[0]=>vic
)
Upvotes: 0
Views: 8666
Reputation: 1
This is a comma-separated value not exactly column-wise. If you have a comma in column value so it will also break your string.
$file = $_FILES['file']['tmp_name']; $handle = fopen($file, "r");
while(($filesop = fgetcsv($handle, 100000, ",")) !== false){
$abc= $filesop[0];
$xyz= $filesop[1];
}
Upvotes: 0
Reputation: 775
Without one unnecessary for cicle :
$handle = fopen($name, "r");
$first_row = true;
$final_ata = array();
$headers = array();
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if($first_row) {
$headers = $data;
$first_row = false;
} else {
$final_ata[] = array_combine($headers, array_values($data));
}
}
echo '<pre>';
print_r($final_ata);die;
will give you result:
Array
(
[0] => Array
(
[column1] => value
[column2] => value
[column3] => value
)
[1] => Array
(
[column1] => value
[column2] => value
[column3] => value
)
[2] => Array
..............
Upvotes: 1
Reputation: 5805
you can use the fgetcsv
function:
if (($handle = fopen("inputfile.csv", "r")) !== false) {
$filesize = filesize("inputfile.csv");
$firstRow = true;
$aData = array();
while (($data = fgetcsv($handle, $filesize, ";")) !== false) {
if($firstRow) {
$aData = $data;
$firstRow = false;
} else {
for($i = 0;$i < count($data); $i++) {
$aData[$i][] = $data[$i];
}
}
}
fclose($handle);
}
so you will get an multidimensional array with first row of headers.
Upvotes: 3
Reputation: 33502
You can open the file using fopen() as usual, get each line by using fgets() and then simply explode it on each comma like this:
<?php
$handle = @fopen("/tmp/inputfile.txt", "r");
if ($handle)
{
while (($buffer = fgets($handle)) !== false)
{
$array=explode(",",$buffer);
print_r($array)
// You have your array at this point.
}
if (!feof($handle))
{
echo "Error: unexpected fgets() fail\n";
}
fclose($handle);
}
?>
Upvotes: 2