search
尋找貓咪~QQ 地點 桃園市桃園區 Taoyuan , Taoyuan

PHP CSV檔案讀寫範例 – jashliao部落格

PHP CSV檔案讀寫範例


 

資料來源: http://jashliao.pixnet.net/blog/post/206848009

 

phpheaderutf-8fopenfwritefclosefile_existsfeofissetUndefined offsetforeachcount(陣列名稱)forexplode、切割字串

 

Create_csv.php

  header(“Content-Type:text/html;
charset=utf-8”);//PHP
亂碼

  $filename
= “ms_my_pg.csv”;

  $myfile
= fopen($filename, “w”) or die(“Unable to open file!”);

  $txt
= “id,name,age\n”;

  fwrite($myfile,
$txt);

  $txt
= “01,’
廖晅晢‘,34\n”;

  fwrite($myfile,
$txt);

  fclose($myfile);

  echo
“create_csv.php done…”;

?>

 

Read_csv.php

  header(“Content-Type:text/html;
charset=utf-8”);//PHP
亂碼

  $filename
= “ms_my_pg.csv”;

  if(file_exists($filename))

  {

     $file
= fopen($filename, “r”);

     if($file
!= NULL)

     {

       echo

單純一行一行列印:
”;

       while
(!feof($file))

       {

          $str
= fgets($file);

          if($str!=”)//因為換行符號也算一行,所以雖然只有兩行資料,但是會有三行數據

          {

            echo
$str.”
”;

          }

       }

       fclose($file);

     }

    

     $file1
= fopen($filename, “r”);

     if($file1
!= NULL)

     {

       echo

拆解列印:
”;

       while
(!feof($file1))

       {

          $str
= fgets($file1);

          $output
= explode(“,”, $str);

          /*

          //方法01

          //Undefined
offset
的解决方法

          $value[0]=isset($output[0])?$output[0]:”;

          $value[1]=isset($output[1])?$output[1]:”;

          $value[2]=isset($output[2])?$output[2]:”;

         

          echo
$value[0].”   “.$value[1].”   “.$value[2].”
”;

          */

          /*

          //方法02

         $str=”;

          foreach
($output as $value )

          {

            $str.=$value.”   “;

          }

          $str.=”
”;

          echo
$str;

          */

          $str=”;

          $len=0;

          $len=count($output);

          if($len>1)//因為換行符號也算一行,所以雖然只有兩行資料,但是會有三行數據

          {

            for($i=0;$i

            {

               $str
.=$output[$i].”   “;

            }

            $str
.=”
”;

            echo
$str;

          }

 

       }

       fclose($file1);      

     }

  }

  echo
“Read_csv.php done…”;

?>

 


 




熱門推薦

本文由 jashliaoeuwordpress 提供 原文連結

寵物協尋 相信 終究能找到回家的路
寫了7763篇文章,獲得2次喜歡
留言回覆
回覆
精彩推薦