gpt4 book ai didi

php - 在php中将mysql数据导出为CSV

转载 作者:行者123 更新时间:2023-11-29 13:56:20 24 4
gpt4 key购买 nike

在我的代码中,我需要在 CSV 导出中保留 mysql 表中每个字段中的所有逗号...

为此,我对所有字段使用了双引号。这段代码在Linux系统中完美运行。在Windows中运行相同的代码时,双引号也显示在导出的CSV文件中。这有什么问题?谁能告诉我为什么会这样?

    function  arrayToCSV($array, $header_row = true, $col_sep = ",", $row_sep = "\n", $qut = '"',$pgeTyp ="")
{
/*col_sep =htmlentities($col_sep);
$row_sep =htmlentities($row_sep);
$qut =htmlentities($qut);*/
if (!is_array($array) or !is_array($array[0])) return false;
//Header row.
if ($header_row)
{
foreach ($array[0] as $key => $val)
{
//Escaping quotes.
$key = str_replace($qut, "$qut$qut", $key);
$output .= $col_sep.$qut.$key.$qut;
}
$output = substr($output, 1)."\n".$row_sep;
}
//Data rows.
foreach ($array as $key => $val)
{
$tmp = '';

foreach ($val as $cell_key => $cell_val)
{
if($pgeTyp!="twitter" && $pagTyp!="jigsaw" && $pgeTyp=="")
$timeValue = @checkTimeStamp($cell_val);
else $timeValue = '';
if($timeValue=="True")
{
$cell_val = str_replace($qut, "$qut$qut", convert_time_zone($cell_val,'d-M-y h:i:s'));
}
else
{
$cell_val = str_replace($qut, "$qut$qut", $cell_val);
}

$tmp .= $col_sep.$qut.$cell_val.$qut;
}
$output .= substr($tmp, 1).$row_sep;
}
return $output;
}

函数调用是,

$dbResult1[] =array('url_twitter_userid' => $selecttwittermainFtch['url_twitter_userid'],'url_tweet_name' => "$url_tweet_name",'url_twitter_uname' => "$url_twitter_uname",'url_twitter_url' => $selecttwittermainFtch['url_twitter_url'],'url_twitter_location' => "$url_twitter_location",'url_twitter_followers' => $selecttwittermainFtch['url_twitter_followers'],'url_twitter_following' => $selecttwittermainFtch['url_twitter_following'],'url_modified_on' => $modifiedon);   
echo arrayToCSV($dbResult1, true, ", ", "\n", '','twitter');

最佳答案

试试这个:

function sqlQueryToCSV($filename, $query)
{
$result = mysql_query($query);
$num_fields = mysql_num_fields($result);
$headers = array();
for ($i = 0; $i < $num_fields; $i++) {
$headers[] = mysql_field_name($result , $i);
}
$fp = fopen(mysql_real_escape_string(getcwd().'\\'.$filename), 'w');
if ($fp) {
fputcsv($fp, $headers);
while ($row = mysql_fetch_array($result)) {
$arrayValues = array();
foreach ($headers as $header)
{
$arrayValues[] = $row[$header];
}
fputcsv($fp, $arrayValues);
}
}
fclose($fp);
}

来源:http://forums.exchangecore.com/topic/907-function-to-convert-mysql-query-to-csv-file-with-php/

关于php - 在php中将mysql数据导出为CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15811101/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com