Pregunta

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.

¿Fue útil?

Solución

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);

Otros consejos

The error messages are so clear that there is nothing better to say.

Simply create each line ($newCsvData array field) as array:

$newCsvData[] = array($catresult->term_id);

This way you will have each line in a CSV file with 1 column.

If you would like to have a CSV file with for example 3 columns, use this:

$newCsvData[] = array(
    $catresult->term_id,
    $catresult->another_filed,
    $catresult->yet_another_field
);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top