【问题标题】:How to Create a CSV file using PHP (and upload it)如何使用 PHP 创建 CSV 文件(并上传)
【发布时间】:2010-12-13 11:27:50
【问题描述】:

例如,我有一个变量“$foo”,其中包含我想在 CSV 中显示的所有数据:

$foo = "some value,another value,last value";

我的目标是:

  1. 创建一个名为“some.csv”的CSV文件,其内容等于$foo

  2. 将“some.csv”上传到我的服务器。

如何做到这一点?

更新:这是对我有用的确切代码。

$foo = "some value,another value,last value";
$file = 'some_data.csv';
file_put_contents($file, $foo);

【问题讨论】:

  • 所以你在家里运行 php 并且你想把它上传到你的服务器?
  • 不,我正在将我的 php 脚本上传到服务器,该服务器将由 chron 作业运行。该脚本应创建一个 csv 文件并将其添加到同一托管空间/服务器上的目录中。

标签: php file csv file-upload


【解决方案1】:

fputcsv()

如果 $foo 已经是 csv 格式。你可以使用file_put_contents()

您没有指定上传方法。这是一个使用 ftp (UNSECURE) 的示例:

$foo = '...csv data...';
$username = "myUser";
$password = "myPassword";
$url = "myserver.com/file.csv";
$hostname= "ftp://$username:$password@$url";
file_put_contents($hostname, $foo);

【讨论】:

    【解决方案2】:

    1 号:

    file_put_contents("foobar.csv", $yourString);
    

    2号:

    $c = curl_init("http://"...);  
    curl_setopt($c, CURLOPT_POSTFIELDS, array('somefile' => "@foobar.csv"));
    $result = curl_exec($c);
    curl_close($c);
    print_r($result);
    

    注意文件名前的@

    【讨论】:

    • 不要忘记检查以确保安装了 cURL 扩展。
    【解决方案3】:

    如果您已经拥有包含所有数据的变量,则可以使用 file_put_contents 将其保存为 csv

    【讨论】:

      【解决方案4】:

      要创建 CSV,您需要将字符串分解为数组,然后循环遍历它。之后,您可以将文件保存到 Web 服务器帐户在您的服务器上可以访问的任何目录。这是一个例子......

      //variables for the CSV file
      $directory = '/sampledir/';
      $file = 'samplefile.csv';
      $filepath = $directory.$file;
      
      //open the file
      $fp = fopen("$filepath",'w+');
      
      //create the array
      $foo = "some value,another value,last value";
      $arrFoo = explode(',',$foo);
      
      //loop through the array and write to the file
      $buffer = '';
      foreach($arrFoo AS $value) {
         $buffer .= $value."\r\n";
      } 
      fwrite($fp,$buffer);
      
      //close the file
      fclose($fp);
      

      您的文件现在将写入$directory 中设置的目录,文件名设置在$file 中。

      -贾斯汀

      【讨论】:

        【解决方案5】:

        如何使用 PHP 上传 CSV 文件(工作代码

        查询库

        <?php 
        class query{
        
        function mysql_query_string($string){
            $enabled = true;
            $htmlspecialchars = false; # Convert special characters to HTML entities 
            /****************************************************************
            The translations performed are: 
        
            '&' (ampersand) becomes '&amp;' 
            '"' (double quote) becomes '&quot;' when ENT_NOQUOTES is not set. 
            ''' (single quote) becomes '&#039;' only when ENT_QUOTES is set. 
            '<' (less than) becomes '&lt;' 
            '>' (greater than) becomes '&gt;' 
        
            *****************************************************************/
        
            if($htmlspecialchars){
            # Convert special characters to HTML entities 
            $string = htmlspecialchars($string, ENT_QUOTES);
            }
            else{
            /****************************************************************
            '"' (double quote) becomes '&quot;' 
            ''' (single quote) becomes '&#039;' 
            ****************************************************************/
            //$string = str_replace('"',"&quot;",$string);
            //$string = str_replace("'","&#039;",$string);
            }
        
            if($enabled and gettype($string) == "string"){
                # Escapes special characters in a string for use in a SQL statement
                return mysql_real_escape_string(trim($string));
            }
            elseif($enabled and gettype($string) == "array"){
            $ary_to_return = array();
            foreach($string as $str){
                $ary_to_return[]=mysql_real_escape_string(trim($str));
            }
                return $ary_to_return;
            }
            else{
                return trim($string);
            }
           }
         }
         ?>
        

        调用 Csv 方法

         public function csvFileSubmitData(){
        
            $this->load->library('query');
            $query=new query();
            $root = DIR_PATH.'public/administrator/csv/';
        
            $fileToUpload= (isset($_FILES['fileToUpload']) and $_FILES['fileToUpload']['size'] > 0 and
            $_FILES['fileToUpload']['error'] == 0) ? $_FILES['fileToUpload'] : "";
        
               if(is_array($fileToUpload)){ # CHECK UPLOADED FILE 1 FOR VALIDATION
                    $fileToUpload['name'] = str_replace(" ","_",$fileToUpload['name']);
                    $fileToUpload['name'] = str_replace("&","and",$fileToUpload['name']);
                    # CHECK FILE TYPE IF IT IS IMAGE JPG,GIF,PNG ETC
                    $fnarr = explode(".", $fileToUpload['name']);
                }   
        
            $rand = rand(1000,10000);
            $filecsv = $rand."_".$fileToUpload['name'];
            $file1  =   $root.$filecsv;
            move_uploaded_file($fileToUpload['tmp_name'],$file1);
        
            $fieldseparator = ",";
            $lineseparator = "\n";
            $csvfile = $file1;
            $addauto = 0;
            $save = 0;
            $outputfile = "output.sql";
            if(!file_exists($csvfile)) {
                echo "File not found. Make sure you specified the correct path.\n";
                exit;
            } 
           $file = fopen($csvfile,"r");
        
            if(!$file) {
                echo "Error opening data file.\n";
                exit;
            }
        
            $size = filesize($csvfile);
        
            if(!$size) {
                echo "File is empty.\n";
                exit;
            }
        
            $csvcontent = fread($file,$size);
        
            fclose($file);
        
            $lines = 1;
            $queries = "";
            $linearray = array();
            $values = "";
            $m =0;
            $linestext = split($lineseparator,$csvcontent);
        
            foreach($linestext as $line){
            if($m++==0){
              continue;
            }
        
            $lines++;
            $line = trim($line," \t");
            if($line  == ''){
              break;
            }
            $linearray = explode($fieldseparator,$line);
        
            $topicname = $linearray[0];
            $question = $linearray[1];
            $answer1 = $linearray[2];
        
            if(isset($linearray[1]) and $linearray[1] != ''){
        
                        $topicname = $query->mysql_query_string($linearray[0]);
                        $question = $query->mysql_query_string($linearray[1]);
                        $answer_type = $query->mysql_query_string($linearray[2]);
            }
            //Save Csv data in your table like this
            //query(insert into topics SET `topic`='".$topicname."',`question`='".$question."');
          }}
        

        如果您使用的是 Codeignitor 框架,因此此代码太容易集成,没有硬性规定,您也可以使用此代码纯 PHP 以及.....

        谢谢 阿都沙末

        【讨论】:

          猜你喜欢
          • 2020-12-21
          • 2016-12-06
          • 1970-01-01
          • 2017-04-17
          • 2014-06-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多