search
HomeBackend DevelopmentPHP Tutorialphp读取excel文件,输出的值乱码解决方法

php读取excel文件,输出的值乱码
$handle = fopen("./home.csv","r");
 while($items = fgetcsv($handle,1000)){
  foreach($items as $k=>$v){
  $v = iconv('gb2312','utf-8',$v); 
  var_dump($v);
  }  
 }

------解决方案--------------------
明白了,你说的是这个问题
这是 php5.3 的一个BUG,php5.2 是正常的

你得换个方法解决了
------解决方案--------------------

PHP code
$fname = $_FILES['MyFile']['tmp_name'];//获取上传的CSV文件    $handle=fopen("$fname","r");//打开文件        //判断导入文件类型是否为csv    //如果为csv继续执行    if($_FILES['MyFile']['type'] !='application/vnd.ms-excel')    {    if($_FILES['MyFile']['type'] != 'text/comma-separated-values')      {        echo "<script>alert('您上传的文件类型不符,请重新上传');window.location='subHotel_import.php';</script>";exit();      }    }              $num = 1;        $total_num = 100;//设置每次添加的数据条数        //删除表中原有数据       $db->query("delete from hotel_activities_2");      //打开导入的csv      //循环添加到表中      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]."',$subHotel_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 "<script>alert('导入成功!!!');window.location='subHotel_query_file.php';</script>";            }else            {            echo "<script>alert('导入失败!!!');window.location='subHotel_import.php';</script>";            }                                             fclose($handle);<br><font color="#e78608">------解决方案--------------------</font><br>在 csv 格式标准中:字符串是需要用双引号括起的,但微软的工具软件却偏偏不加这个双引号<br>在 php5.3 以前的版本中,php 也认同这种做法<br>但自 php5.3 起,微软摆出了不合作姿态,于是 fgetcsv 也就残废了<br><font color="#e78608">------解决方案--------------------</font><br>读取excel数据要用到一个插件,直接这样读取肯定是不行的。<br>下面这个是将ecxcel数据读取到数据库的方法:<br>7.$handle = fopen (”test.csv”,”r”); <br>8.$sql=”insert into scores(idcard,names ,num,sex,nation,score) values(’”; <br>9.while ($data = fgetcsv ($handle, 1000, “,”)) { <br>10.$num = count ($data); <br>11.for ($c=0; $c 12.if($c==$num-1){$sql=$sql.$data[$c].”‘)”;break;} <br>13.$sql=$sql.$data[$c].”‘,’”; <br>14.} <br>15.print “”; <br>16.echo $sql.””; <br>17.$db->query($sql); <br>18.echo “SQL语句执行成功!”; <br>19.$sql=”insert into scores(idcard,names ,num,sex,nation,score) values(’”; <br>20.} <br>21.fclose ($handle); <br>22.$time_end = getmicrotime();<div class="clear">
                 
              
              
        
            </div>
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What data can be stored in a PHP session?What data can be stored in a PHP session?May 02, 2025 am 12:17 AM

PHPsessionscanstorestrings,numbers,arrays,andobjects.1.Strings:textdatalikeusernames.2.Numbers:integersorfloatsforcounters.3.Arrays:listslikeshoppingcarts.4.Objects:complexstructuresthatareserialized.

How do you start a PHP session?How do you start a PHP session?May 02, 2025 am 12:16 AM

TostartaPHPsession,usesession_start()atthescript'sbeginning.1)Placeitbeforeanyoutputtosetthesessioncookie.2)Usesessionsforuserdatalikeloginstatusorshoppingcarts.3)RegeneratesessionIDstopreventfixationattacks.4)Considerusingadatabaseforsessionstoragei

What is session regeneration, and how does it improve security?What is session regeneration, and how does it improve security?May 02, 2025 am 12:15 AM

Session regeneration refers to generating a new session ID and invalidating the old ID when the user performs sensitive operations in case of session fixed attacks. The implementation steps include: 1. Detect sensitive operations, 2. Generate new session ID, 3. Destroy old session ID, 4. Update user-side session information.

What are some performance considerations when using PHP sessions?What are some performance considerations when using PHP sessions?May 02, 2025 am 12:11 AM

PHP sessions have a significant impact on application performance. Optimization methods include: 1. Use a database to store session data to improve response speed; 2. Reduce the use of session data and only store necessary information; 3. Use a non-blocking session processor to improve concurrency capabilities; 4. Adjust the session expiration time to balance user experience and server burden; 5. Use persistent sessions to reduce the number of data read and write times.

How do PHP sessions differ from cookies?How do PHP sessions differ from cookies?May 02, 2025 am 12:03 AM

PHPsessionsareserver-side,whilecookiesareclient-side.1)Sessionsstoredataontheserver,aremoresecure,andhandlelargerdata.2)Cookiesstoredataontheclient,arelesssecure,andlimitedinsize.Usesessionsforsensitivedataandcookiesfornon-sensitive,client-sidedata.

How does PHP identify a user's session?How does PHP identify a user's session?May 01, 2025 am 12:23 AM

PHPidentifiesauser'ssessionusingsessioncookiesandsessionIDs.1)Whensession_start()iscalled,PHPgeneratesauniquesessionIDstoredinacookienamedPHPSESSIDontheuser'sbrowser.2)ThisIDallowsPHPtoretrievesessiondatafromtheserver.

What are some best practices for securing PHP sessions?What are some best practices for securing PHP sessions?May 01, 2025 am 12:22 AM

The security of PHP sessions can be achieved through the following measures: 1. Use session_regenerate_id() to regenerate the session ID when the user logs in or is an important operation. 2. Encrypt the transmission session ID through the HTTPS protocol. 3. Use session_save_path() to specify the secure directory to store session data and set permissions correctly.

Where are PHP session files stored by default?Where are PHP session files stored by default?May 01, 2025 am 12:15 AM

PHPsessionfilesarestoredinthedirectoryspecifiedbysession.save_path,typically/tmponUnix-likesystemsorC:\Windows\TemponWindows.Tocustomizethis:1)Usesession_save_path()tosetacustomdirectory,ensuringit'swritable;2)Verifythecustomdirectoryexistsandiswrita

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment