I appreciate there are already a lot of questions around this subject. But, as I\'m not a PHP developer, I\'m struggling to get anything to work for my specific object struc
I've created a function for that before. Bare in mind the code bellow does not assume there is any csv headers.
function doCSV($file, $content = array())
{
$handle = fopen($file, "w");
foreach($content as $value) {
fputcsv($handle, array(key($content), $value));
}
fclose($handle);
}
doCSV("test.csv", array("Test 1" => "Value 1", "Test 2" => "Value 2"));
If this is not what you're asking for let me know, I'll edit the answer.
For writing a PHP array to a CSV file you should use the built in PHP function fputcsv
:
<?php
$list = array (
array('header 1', 'header 2', 'header 3', 'header 4'),
array('5656', '454545', '5455', '5454'),
array('541212', '454545', '5455', '5454'),
array('541212', '454545', '5455', '5454'),
);
$fp = fopen('file.csv', 'wb');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
Edit:
More specific example based on your data input:
<?php
// I had to recreate your data, this is just an example
$array_of_objects = array();
for( $i = 0; $i < 5; $i++ )
{
$obj = new \stdClass();
$obj->username = "Rein";
$obj->answer = "Correct";
$obj->awesomeness = 1000;
$array_of_objects[] = $obj;
}
// Open a file to write to
$fp = fopen('file.csv', 'wb');
$i = 0;
// Loop the array of objects
foreach( $array_of_objects as $obj )
{
// Transform the current object to an array
$fields = array();
foreach ($obj as $k => $v)
{
$fields[ $k ] = $v;
}
if( $i === 0 )
{
fputcsv($fp, array_keys($fields) ); // First write the headers
}
fputcsv($fp, $fields); // Then write the fields
$i++;
}
fclose($fp);
Edit 2:
Based on new information (you have a JSON string to start with), I'm added this example as a better way to write the data to a CSV file:
<?php
$data = json_decode($_POST['data'], TRUE);
$records = $data['records'];
$fp = fopen('records.csv', 'wb');
$i = 0;
foreach ($records as $record) {
if($i === 0) {
fputcsv($fp, array_keys($record));
}
fputcsv($fp, array_values($record));
$i++;
}
fclose($fp);
Try below solution header of csv will be (item, cost, approved by) - replace $data
with your array variable:
$data = array(
array( 'item' => 'Server', 'cost' => 10000, 'approved by' => 'Joe'),
array( 'item' => 'Mt Dew', 'cost' => 1.25, 'approved by' => 'John'),
array( 'item' => 'IntelliJ IDEA', 'cost' => 500, 'approved by' => 'James')
);
$fp = fopen('file.csv', 'w');
$i = 0;
foreach ($data as $fields) {
if($i == 0){
fputcsv($fp, array_keys($fields));
}
fputcsv($fp, array_values($fields));
$i++;
}
fclose($fp);
for more detail have alook at : PHP: fputcsv - Manual