简体   繁体   English

如何使用PHP创建CSV文件(并上传)

[英]How to Create a CSV file using PHP (and upload it)

For example, I have a variable "$foo" that includes all the data which I want to show in the CSV: 例如,我有一个变量“ $ foo”,其中包含我要在CSV中显示的所有数据:

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

My goal is to: 我的目标是:

  1. Create a CSV file named "some.csv" whose contents are equal to $foo 创建一个名为“ some.csv”的CSV文件,其内容等于$ foo

  2. Upload "some.csv" to my server. 将“ some.csv”上传到我的服务器。

How can this be done? 如何才能做到这一点?

Update: Here's the exact code that worked for me. 更新:这是对我有用的确切代码。

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

See fputcsv() 参见fputcsv()

If $foo is already csv-formatted. 如果$ foo已经是csv格式的。 You can use file_put_contents() 您可以使用file_put_contents()

You don't specify the upload method. 您没有指定上传方法。 Here is an example using ftp (UNSECURE): 这是使用ftp(UNSECURE)的示例:

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

Number 1: 1号:

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

Number 2: 2号:

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

note the @ before the filename 注意文件名前的@

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

How to upload CSV file using PHP ( Working Code ) 如何使用PHP上传CSV文件( 工作代码

Query Library 查询库

<?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);
    }
   }
 }
 ?>

Call Csv Method 呼叫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."');
  }}

If you are using Codeignitor Framework so this code is too easy to integrate ,No hard&fast rule you can also use this code plain PHP as well as ..... 如果您使用的是Codeignitor Framework,那么此代码太容易集成了,没有硬性规定,您也可以使用纯PHP以及...

Thanx AbdulSamad 桑克斯·阿卜杜勒·萨马德(Thanx AbdulSamad)

To create the CSV you would need to break your string into an array, then loop through it. 要创建CSV,您需要将字符串分成一个数组,然后遍历它。 After that you can save the file to any directory the web server account has access to on your server. 之后,您可以将文件保存到Web服务器帐户有权访问的任何目录。 Here is an example ... 这是一个例子...

//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);

Your file will now be written to the directory set in $directory with the filename set in $file . 现在,您的文件将被写入$directory设置的$directory ,文件名将在$file设置。

-Justin -Justin

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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