Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write PHP array object to a csv file

Tags:

arrays

php

csv

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

like image 355
Arushi Chopra Avatar asked Oct 08 '15 13:10

Arushi Chopra


People also ask

How do I pass an array into a CSV file?

To convert an array into a CSV file we can use fputcsv() function. The fputcsv() function is used to format a line as CSV (comma separated values) file and writes it to an open file.

How do I store form data in a CSV file?

For make this type of system here we have use PHP script. We have use some PHP in build function like fopen() for open file for write operation, file() function for get file data in array format for count number of rows in file and fputcsv() function for write form data in csv file.

How does PHP Fputcsv work?

fputcsv() function in PHP The fputcsv() function formats a line as CSV and writes it to an open file. The function returns the length of the written string.


2 Answers

Try following

<?php

//$list = ----your array

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

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

fclose($fp);
?>
like image 72
Rohit Kumar Avatar answered Sep 20 '22 17:09

Rohit Kumar


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);
?>
like image 30
Chizzle Avatar answered Sep 21 '22 17:09

Chizzle