PHP read Excel file, output value garbled
$handle = fopen ("./home.csv", "R");
while ($items = Fgetcsv ($handle, 1000)) {
foreach ($items as $k = = $v) {
$v = Iconv (' gb2312 ', ' utf-8 ', $v);
Var_dump ($v);
}
}
------Solution--------------------
See, you're talking about the problem.
It's a bug,php5.2 of php5.3, it's normal.
You're going to have to deal with this in a different way
------Solution--------------------
PHP Code
$fname = $_files[' MyFile ' [' tmp_name '];//obtain the uploaded CSV file $handle =fopen ("$fname", "R");//Open File//Determine if the import file type is CSV// CSV continues to execute if ($_files[' MyFile ' [' type ']! = ' Application/vnd.ms-excel ') {if ($_files[' MyFile ' [' type ']! = ' text/comma- Separated-values ') {echo ""; exit (); }} $num = 1; $total _num = 100;//Sets the number of data bars per Add//delete the original data in the table $db->query ("Delete from hotel_activities_2"); Open the imported CSV//loop added to the table while (!feof ($handle)) {$content = Fgets ($handle) ; $data = Preg_split ("/,/", $content); if ($data [0] = = ") {continue; } $subHotel _id = preg_replace ('/[^0-9]/', ' ', $data [0]); $subHotel _type= (int) preg_replace ('/[^0-9]/', ', $data [4]); if ($num = = $total _num) {$num = 1; $values. = "($subHotel _id, '". $data [1]. "', '". $DATA[2]. "', '". $data [3]. "', $subHotel _type),"; $values = RTrim ($values, ', '); $sql = "INSERT into hotel_activities_2 (Hotel_id,start_date,end_date,content,s_type) values". $values; $AAA = $db->query ($sql); $values = "; } else {$values. = "($subHotel _id, '". $data [1]. "', '". $data [2]. "', '". $data [3]. "', $s Ubhotel_type), "; $num + +; }} if (mysql_error!==1) {$values = RTrim ($values, ', '); $sql = "INSERT into hotel_activities_2 (Hotel_id,start_date,end_date,content,s_type) values". $values; $db->query ($sql); echo ""; }else {echo ""; } fclose ($handle);
------Solution--------------------
In the CSV format standard: strings need to be enclosed in double quotes, but Microsoft's tool software does not add this double quotation mark
In previous versions of php5.3, PHP was also in agreement with this practice
But since php5.3, Microsoft has assumed the gesture of non-cooperation, so fgetcsv also crippled
------Solution--------------------
Reading the Excel data to use a plug-in, the direct reading of this must not be.
Here's how to read ecxcel data to a database:
7. $handle = fopen ("Test.csv", "R");
8. $sql = "INSERT into scores (Idcard,names, Num,sex,nation,score) VALUES ('";
9.while ($data = Fgetcsv ($handle, 1000, ",")) {
$num = count ($data);
11.for ($c =0; $c < $num; $c + +) {
12.if ($c = = $num-1) {$sql = $sql. $data [$c]. "')"; break;}
$sql = $sql. $data [$c]. "', '";
14.}
15.print "< br>";
16.echo $sql. " < br> ";
$db->query ($sql);
18.echo "SQL statement executed successfully! < br> ";
$sql = "INSERT into scores (Idcard,names, Num,sex,nation,score) VALUES ('";
20.}
21.fclose ($handle);
$time _end = Getmicrotime ();