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 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计