开发者

How to store each row of the csv file to array in php

I have data in csv file as follows.

Mr,Vinay,H S,Application Engineer,v开发者_StackOverflowinay.hs@springpeople.com,99005809800,Yes Mr,Mahammad,Hussain,Application Engineer,vinay.hs@springpeople.com,99005809800,Yes

I want to store each row in each array.explain me how to do that


I did not understand each row in each array.

use fgetcsv() function to read the CSV file php.

An example

<?php
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        echo "<p> $num fields in line $row: <br /></p>\n";
        $row++;
        for ($c=0; $c < $num; $c++) {
            echo $data[$c] . "<br />\n";
        }
    }
    fclose($handle);
}
?>

OR If you want to store them in an array you could use

$data = array();
if (($handle = fopen("test.csv", "r")) !== FALSE) {
    while(($row = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $data[] = $row;
    }
}


Assuming the CSV is a file (if not, make the CSV match the $csv, which is essentially the file broken down in the separate lines), here is a very simple way:

$csv = file('mycsv.csv'); $result = array();
//iterate the lines
foreach ($csv as $line)
  // I'd recommend  more robust "csv-following" method though (fgetcsv maybe)
  $result[] = explode(',',$result); 
//show the results
print_r($result);

Though fgetcsv is probably a safer bet (as others have mentioned) (See the docs).


To further extend your comment:

//iterate the lines
foreach ($csv as $line)
  // I'd recommend  more robust "csv-following" method though (fgetcsv maybe)
  $result[] = explode(',',$result); 

can become:

//iterate the lines
foreach ($csv as $line)
  // combine the current results with the new results
  $result = array_marge($result,$line);

or, if order is important:

//iterate the lines
foreach ($csv as $line)
  // add each result on to the end of the result array
  foreach($line as $val)
    // add each value
    $result[] = $val;


You can use fgetcsv() for that:

$data = array();
if (($handle = fopen("test.csv", "r")) !== FALSE) {
    while(($row = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $data[] = $row;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜