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 :)
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.
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.
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.
Try following
<?php
//$list = ----your array
$fp = fopen('file.csv', 'w');
foreach ($list as $fields) {
fputcsv($fp,get_object_vars($fields));
}
fclose($fp);
?>
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);
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With