Im traying to export some data to csv. I can print the data in the web but when i save it to a csv file it shows this:
Column 1,"Column 2"
Array,"Acme (Sample)",0011U00000AnbfaQAB
Array,"Global (Sample)",0011U00000AnbfbQAB
How can i get rid of the "Array,"?
I get the data here and print it:
foreach ($records as $record)
{
print 'Name :';
print htmlspecialchars($record['Name']);
print ' - ';
print htmlspecialchars($record['Id']);
print '<br/>';
print "\n";
}
This is a code to save the data to csv:
$file = fopen('toNavasoft.csv', 'w');
// save the column headers
fputcsv($file, array('Column 1', 'Column 2'));
// save each row of the data
foreach ($records as $record)
{
fputcsv($file, $record);
}
// Close the file
fclose($file);
I just added this:
var_export ($records);
and the output is:
array ( 0 => array ( 'attributes' => array ( 'type' => 'Account', 'url' => '/services/data/v20.0/sobjects/Account/0011U00000AnbfaQAB', ), 'Name' => 'Acme (Sample)', 'Id' => '0011U00000AnbfaQAB', ), 1 => array ( 'attributes' => array ( 'type' => 'Account', 'url' => '/services/data/v20.0/sobjects/Account/0011U00000AnbfbQAB', ), 'Name' => 'Global (Sample)', 'Id' => '0011U00000AnbfbQAB', ), )
I expect the output like:
Column 1,Column 2
Acme (Sample),0011U00000AnbfaQAB
Global (Sample),0011U00000AnbfbQAB
You can use the fputcsv , uing the code bellow :
<?php
$result = array(['column1', 'column2']);
foreach($records as $record){
$result[] = [$record['Name'],$record['Id']];
}
$fp = fopen('toNavasoft.csv', 'w');
foreach ($result as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
?>
The point here is to select the data you want to persist in the cv file into $result variable and then continue what you already try to do .
Hope this help you.