8

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

1

2 Answers 2

23

Try following

<?php

//$list = ----your array

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

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

fclose($fp);
?>
Sign up to request clarification or add additional context in comments.

1 Comment

Thankyou so much! I can't give upvote as of now. You are awesome!
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);
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.