doudeng5764 2014-05-07 23:24
浏览 47
已采纳

mysql结果到数组写入csv文件?

So I have never wrote to a csv file before but always read from a csv file. Based on some example I have read this is what I have tried.

<?php
$newCsvData = array();
$getCats = "SELECT * FROM $termTax WHERE taxonomy = 'product_cat'";
$catresults = $wpdb->get_results($getCats);

foreach( $catresults as $catresult ) {
  $newCsvData[] = $catresult->term_id;
}
  $handle = fopen('export.csv', 'w');
  foreach ($newCsvData as $line) {
     fputcsv($handle, $line);
  }
  fclose($handle);
?>

I end up with errors saying fputcsv() expects parameter 2 to be array, string given in that is for this line

fputcsv($handle, $line);

If I var_dump($catresult); I get everything in the row as expected in an array... Example

object(stdClass)#401 (6) { ["term_taxonomy_id"]=> string(3) "224" ["term_id"]=> string(2) "37" ["taxonomy"]=> string(11) "product_cat" ["description"]=> string(0) "" ["parent"]=> string(1) "0" ["count"]=> string(1) "0" } object(stdClass)#402 (6) { ["term_taxonomy_id"]=> string(2) "35" ["term_id"]=> string(2) "35" ["taxonomy"]=> string(11) "product_cat" ["description"]=> string(0) "" ["parent"]=> string(1) "0" ["count"]=> string(1) "1" } 

I just don't know how to write the array to the csv...

If I var_dump($line) I get string(2) "37" each string and its the correct value.

Am I on the right path? Thanks in advance.

UPDATE: So I created a blank php file in the root of my wordpress install and used this code and it works find... well some code someone below fixed... But the thing is it will not work from within my plugin I am working on.

  • 写回答

2条回答 默认 最新

  • duanhuang4306 2014-05-07 23:28
    关注

    The error message is telling you what is wrong.

    fputcsv() expects parameter 2 to be array

    And from your own admission (emphasis mine)

    If I var_dump($line) I get string(2) "37" each string and its the correct value

    Why not try this? You're building an array already.

    foreach( $catresults as $catresult ) {
        $newCsvData[] = $catresult->term_id;
    }
    fputcsv($handle, $newCsvData);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化