我想将curl数据正确添加到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 file。我希望所有这些数据都在一个单元格中。
像url一样进入下一个单元格的内容。我还尝试this tutorial来正确格式化数据。但它没有按预期工作。
请给出一些指导。
谢谢
答案 0 :(得分:2)
按如下方式更改函数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);
}