tags:

views:

97

answers:

3

Hi,

i am trying to upload an excel file and to store its contents in the Mysql database.

i am having a problem in saving the contents.. like

My csv file is in the form of

        "1","aruna","IEEE 
         paper"
        "2","nisha","JOurnal magazine"

actually i am having 2 records and i am using the code

<?php
  $string = file_get_contents( $_FILES["file"]["tmp_name"] );
  //echo $string;

foreach ( explode( "\n", $string ) as $userString )

    {
                 echo $userString;

            }

?> since in the Csv record there is a new line inserted in between IEEE and paper it is dispaying me as 3 records..

How to remove this new line code wise and to modify the code so that only the new line between the records 1 and 2 is considered... Pls help me....

+1  A: 

Maybe you should be using a library to open and modify excel files. Try with XLS Reader.

metrobalderas
+2  A: 

Use fgetcsv to load an parse CSV files.

pygorex1
Thanks ur suggestion helps me a lot.. And i have simply used ($data = fgetcsv($handle, 1000, ";") with $data as each row.. And it is saving perfectly.. Thank you :)
Aruna
+1  A: 

The fgetcsv command is powerful and useful, you should probably use it. But if you want your original question answered...

  1. replace the "good" newlines with some weird token, like @EOL@
  2. replace the "bad" newlines with another token, like @NL@
  3. replace the first token with a newline
  4. parse your data.

like so...

<?php   
    $txt = <<<_TXT
"1","aruna","IEEE 
paper" "2","nisha","JOurnal magazine"
"2","aruna","IEEE paper" "2","nisha","JOurnal magazine"
"3","aruna","IEEE paper" "2","nisha","JOurnal
magazine"
"4","aruna","IEEE paper" "2","nisha","JOurnal magazine"
_TXT;
    $txt = str_replace("\"\n", "@EOL@", $txt);
    $txt = str_replace("\n", "@NL@", $txt);
    $txt = str_replace("@EOL@", "\n", $txt);
    echo $txt;
?>

The output is...

"1","aruna","IEEE @NL@paper" "2","nisha","JOurnal magazine

"2","aruna","IEEE paper" "2","nisha","JOurnal magazine

"3","aruna","IEEE paper" "2","nisha","JOurnal@NL@magazine

"4","aruna","IEEE paper" "2","nisha","JOurnal magazine"

Vineel Shah
excellent answer! An alternative would be to include logic in your code to determine this. In this case, since the text is qualified, simply keep track of the number of quotation marks; odd means it's a newline within the field, even means that it's a good newline.
Travis Leleu