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
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
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
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.