8

Hello guys just want to ask how can I put an associative array in csv? For example if I have an array like this.

Array
(
    [0] => Array
        (
            [restaurant_id] => 1227
            [new_lat] => 13.62241
            [new_long] => 123.19341
            [date_updated] => 2013-11-14 11:20:26
        )

    [1] => Array
        (
            [restaurant_id] => 1218
            [new_lat] => 14.66732
            [new_long] => 121.02618
            [date_updated] => 2013-11-14 11:22:22
        )
)

For my code in generating csv is this:

            $restaurant_id = $post_data['company_id'];
            $new_lat_entry = $post_data['new_lat'];
            $new_long_entry = $post_data['new_long'];

            $data_add =  array(
                'restaurant_id' => $restaurant_id,
                'new_lat' => $new_lat_entry,
                'new_long' => $new_long_entry,
                'date_updated' => date('Y-m-d H:i:s')
            );

            $data = unserialize(file_get_contents('addresses.txt'));
            $data[] = $data_add;

            $serialize_data = serialize($data);
            file_put_contents("addresses.txt", $serialize_data, LOCK_EX); //write the text file

            $array = unserialize(file_get_contents('addresses.txt')); //THIS WILL GET THE ARRAY
                    echo "<pre>";
            print_r($array); //display it

            $csv = '';
            foreach($array as $row) {
                $csv .= implode(',', $row) . "\n";
            }


            //fn_print_die($csv);


            $file_input = fopen("addresses.csv","w");
            foreach($csv as $line){
                fputcsv($file_input,split(',',$line));
            }
            fclose($file_input);

4 Answers 4

12

This should work...

 <?php

  foreach ($array as $row) {
       fputcsv($file_input, $row);
 }

 fclose($file_input);

  ?>

Just refer to the fputcsv manual on php.net

Sign up to request clarification or add additional context in comments.

2 Comments

The problem with this answer is it doesn't write a header row with the field names in it.
"Warning: fputcsv() expects parameter 1 to be resource, string given"
5

You should try to implement SPL classes when possible:

$csv_file = new SplFileObject('addresses.csv', 'w');

foreach ($address_list as $address_fields) {
    $csv_file->fputcsv($address_fields);
}

Comments

4

You can use implode to do something like this pretty easily

$csv = '';
foreach($array as $row) {
    $csv .= implode(',', $row) . "\n";
}

3 Comments

Ok I added that but it doesn't save as csv. I update my code.
The code above generates a long string, representing the CSV File contents. You will need to still write the string to a File, then close it.
The issue with using this approach to create a CSV is that you won't have proper field enclosure. For example: $array = array( 'one', 'two', 'three,four', 'five'); will result in $csv containing the following string: 'one,two,three,four,five' which, when opened with a csv editor will be translated into five fields/columns, instead of the expected four. Something like fputcsv, however, will handle encapsulating (and escaping) correctly.
4

To make this clean, you would have to

  1. collect all keys from the array (foreach twice)
  2. build a second array with each restaurant (no subnodes)
  3. merge the keys array into that and THEN
  4. merge all restaurant subnodes to those keys.

The reason is simple: restaurant A has "[self_service] => true" The CSV line for restaurant B will either miss a column or worse, have "[vegetarian_food] => false" instead.

In the end, you would have "true" and "false" in the same column under each other, with theo first meaning "Yes, self service" and the second meaning "Sorry veggies". You will probably never notice, because they might still have the same count(array).

(I would write this as a comment, but my Stack Exchange reputation does not allow me that yet (48 now, 2 more to go, yay!)

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.