簡體   English   中英

使用fputcsv()將數據正確添加到csv文件中

[英]Add data into csv file properly using fputcsv()

我想將curl數據正確添加到csv文件中,當我嘗試將數據添加到csv文件中時,數據全部添加到csv文件中..

我只想在cell添加

下面是我的代碼-

<?php

    define('CSV_PATH','csvfiles/');

    $csv_file = CSV_PATH . "file_input_url.csv"; // Name of your input file
    $csvfile = fopen($csv_file, 'r');

    $csv_fileoutput = CSV_PATH . "file_output_content.csv"; // Name of output file
    $csvfileoutput = fopen($csv_fileoutput, 'a');

    header('Content-type: application/csv');
    header('Content-Disposition: attachment; filename=' . $csvfileoutput);
    header("Content-Transfer-Encoding: UTF-8");

    $headers = ['URL','Code_content'];

    fputcsv($csvfileoutput, $headers);
    function cleanData(&$str)
              {
                // escape tab characters
                $str = preg_replace("/\t/", "\\t", $str);

                // escape new lines
                $str = preg_replace("/\r?\n/", "\\n", $str);

                // convert 't' and 'f' to boolean values
                if($str == 't') $str = 'TRUE';
                if($str == 'f') $str = 'FALSE';

                // force certain number/date formats to be imported as strings
                if(preg_match("/^0/", $str) || preg_match("/^\+?\d{8,}$/", $str) || preg_match("/^\d{4}.\d{1,2}.\d{1,2}/", $str)) {
                  $str = "'$str";
                }

                // escape fields that include double quotes
                if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
              }

while($data = fgetcsv($csvfile)) 
    {

        $url = $data[0];
    //  $url = "http://www.partsimple.com/";

        $ch = curl_init();  
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_POST, true);  
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $url); 
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
        //curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        $str = curl_exec ($ch); 
        curl_close ($ch); 

        cleanData($str);

        fputcsv($csvfileoutput,array($url,$str));

    }

?>

更新

這是我通過這段代碼得到的csv文件 我希望所有這些數據都放在一個單元格中。

例如url並進入下一個單元格的內容。

我也嘗試過本教程來正確格式化數據。 但是它沒有按預期工作。

請給一些指導。

謝謝

如下更改函數cleanData()-

function cleanData(&$str)
        {
            //$str = preg_replace("/\t/", "\\t", $str);

            $str = str_replace(array("\n\r", "\n", "\r"), '', $str);

            $str = trim(preg_replace('/\t+/', '', $str));

            $str = preg_replace('/\s+/S', " ", $str);

        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM