Jump to content

php get csv problem


antonykin

Recommended Posts

Hi All,

 

I gotta write a php function to read the content from a csv file.

 

  while (($data = fgetcsv($handle, 1000, "\n")) !== FALSE) {

 

    $data_row = explode("\t",$csv_array[$counter]);

    $cat_info = explode(",",$data_row[0]);

 

I use fgetcsv to open the csv file and use explode function to read the field seperated by ",".

Just, what is very bad is that the file contains some fields like this "abc, def".

 

My function will read that field as two parts: ' "abc ' & ' def" '

 

Any one can give me a hand??  :'(

Link to comment
https://forums.phpfreaks.com/topic/76315-php-get-csv-problem/
Share on other sites

Hi there, below please find the code I write:

 

function add($id=0) {

 

// open csv file: change the path to end-user input path

$handle = fopen(CATEGORY_PATH, "r");

$csv_data = "";

 

while (($data = fgetcsv($handle, 1000, "\n")) !== FALSE) {

$num = count($data);

 

for ($c=0; $c < $num; $c++) {

$csv_data .= $data[$c] . "\n";

}

}

 

$csv_array    = explode("\n",$csv_data);

$column_names = explode("\t",$csv_array[0]);

 

$last_data_row = count($csv_array) - 1;

 

//put csv file content into an array

for($counter = 1; $counter < $last_data_row; $counter++)

{

$data_row = explode("\t",$csv_array[$counter]);

$cat_info = explode(",",$data_row[0]);

 

foreach($data_row as $data_value)

{

$displays[$counter-1]['CategoryDetail']['maincat_en'] = $cat_info[0];

$displays[$counter-1]['CategoryDetail']['seccat_en'] = $cat_info[1];

$displays[$counter-1]['CategoryDetail']['thirdcat_en'] = $cat_info[2];

$displays[$counter-1]['CategoryDetail']['fourthcat_en'] = $cat_info[3];

 

$result= $this->Category->query("select max(id) as id from categories");

$displays[$counter-1]['CategoryDetail']['category_id'] = $result[0][0]['id']+$counter;

$displays[$counter-1]['Category']['id'] = $result[0][0]['id']+$counter;

 

}

}

 

Link to comment
https://forums.phpfreaks.com/topic/76315-php-get-csv-problem/#findComment-386496
Share on other sites

found something for you

 

<?php
$data = 'test,"test , best",test4,test1';


function getCSVValues($string, $separator=",")
{
    $elements = explode($separator, $string);
    for ($i = 0; $i < count($elements); $i++) {
        $nquotes = substr_count($elements[$i], '"');
        if ($nquotes %2 == 1) {
            for ($j = $i+1; $j < count($elements); $j++) {
                if (substr_count($elements[$j], '"') > 0) {
                    // Put the quoted string's pieces back together again
                    array_splice($elements, $i, $j-$i+1,
                        implode($separator, array_slice($elements, $i, $j-$i+1)));
                    break;
                }
            }
        }
        if ($nquotes > 0) {
            // Remove first and last quotes, then merge pairs of quotes
            $qstr =& $elements[$i];
            $qstr = substr_replace($qstr, '', strpos($qstr, '"'), 1);
            $qstr = substr_replace($qstr, '', strrpos($qstr, '"'), 1);
            $qstr = str_replace('""', '"', $qstr);
        }
    }
    return $elements;
}

print_r(getCSVValues($data)); 
?>

 

well you can implement the same wherever you need in your code instead of the explode

Link to comment
https://forums.phpfreaks.com/topic/76315-php-get-csv-problem/#findComment-386555
Share on other sites

Directly from the php manual :

 

array fgetcsv ( resource $handle [, int $length [, string $delimiter [, string $enclosure [, string $escape]]]] )

 

fgetcsv retrieves an array based on the parameters that you specify.

 

Thus fgetcsv($handle, 1000, ',' ,'"') will get the information from a file in the following format

"1","2","3","4"

"a","8","m","p"

 

It returns you an array of arrays.

Thus for row[1] you have the array(1,2,3,4)

for row[2] you have the array (a,8,m,p)

and so on.

 

The 3rd parameter in the array is the field delimiter (,), the 4th the enclosing of each field ("),

The 2nd parameter MUST be longer than the longest line, failure to be longer will cause partial information to be retrieved.

 

Link to comment
https://forums.phpfreaks.com/topic/76315-php-get-csv-problem/#findComment-386558
Share on other sites

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.