简体   繁体   中英

PHP import using txt file

I am using following code for importing data into database using txt file

while (!feof($handle)) // Loop til end of file.
{



    $buffer = fgets($handle, 4096); // Read a line.

    $data_array =explode("|",$buffer);//Separate string by the means of |

    $escaped_array = array_map('mysql_escape_string',$data_array);

    $escaped_array = '("'.implode('","',$escaped_array).'") ';


    if($i !=1) {
       echo $sql = 'INSERT INTO '.$tablename.' VALUES'.$escaped_array; 
        mysql_query($sql) ; //or die(mysql_error().$tablename);// use mysql insert query here
        //exit;
    }

    $i++;
} //end while

it inserting values like INSERT INTO PROVIDER_DEMOGRAPHIC VALUES("10000104","Sand","David","C","MD","Family Practice","","N","N","N","P","125\\r\\r\\n") INSERT INTO PROVIDER_DEMOGRAPHIC VALUES("10000105","Stucky","Mitchell","B","MD","Family Practice","","N","N","N","P","101\\r\\r\\n")

I donot want extra character in last fiels like \\r\\n\\r Please tell me how i can trim it.

You are reading the newline characters from the file, and may need to trim it

Use:

$buffer = fgets($handle, 4096); // Read a line.
$buffer = rtrim($buffer);
$escaped_array = array_map('mysql_escape_string',$data_array);

Warning: mysql_ function is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM