7

I would like to ask that how can I write a php array std object to a csv file.

Convert array to csv Didn't solve my problem.

This is my Array

Array
    (
        [0] => stdClass Object
            (
                [lotNum] => 1
                [commissionRate] => 4.0%
                [detailUrl] => JEq7E6IEa
                [promotionVolume] => 0
                [packageType] => piece
                [price] => US $80.54
                [imageUrl] => BOX.jpg
                [subject] => Box
                [salePrice] => US $60.41
                [commission] => US $0.00
                [productId] => xxxx1
            )

        [1] => stdClass Object
            (
                [lotNum] => 1
                [commissionRate] => 4.0%
                [detailUrl] => JEq7E6IEa
                [promotionVolume] => 0
                [packageType] => piece
                [price] => US $80.54
                [imageUrl] => BOX.jpg
                [subject] => Box
                [salePrice] => US $60.41
                [commission] => US $0.00
                [productId] => xxxx1
            )
    )

How can I put data of each product in one row of csv file? Thanks :)

Community
  • 1
  • 1
Arushi Chopra
  • 101
  • 1
  • 1
  • 6

2 Answers2

23

Try following

<?php

//$list = ----your array

$fp = fopen('file.csv', 'w');

foreach ($list as $fields) {
    fputcsv($fp,get_object_vars($fields));
}

fclose($fp);
?>
Rohit Kumar
  • 1,948
  • 1
  • 11
  • 16
3

You have objects within your array. Convert them to an array.

<?php
$fp = fopen('file.csv', 'w');
foreach ($myArray as $fields) {
    if( is_object($fields) )
        $fields = (array) $fields;
    fputcsv($fp, $fields);
}

fclose($fp);
?>
Chizzle
  • 1,707
  • 1
  • 17
  • 26