Array into a CSV file using same id in PHP

create csv file using php and save it into directory
php array to csv with headers
php csv to array
php get first row of csv file
php loop through csv
php csv header row
php csv library
php csv import

I have an array called : $messages with this data. (Generated dynamically).

How can I create a CSV file which contains 3 columns (txt, time and name) for each txt_id with the values ?

array(3) {
  [0]=>
  array(5) {
    ["txt"]=>
    string(3) "Hey"
    ["txt_id"]=>
    string(1) "5"
    ["name"]=>
    string(8) "John Doe"
    ["id_user"]=>
    string(1) "5"
    ["time"]=>
    string(19) "2017-12-15 08:28:47"
  }
  [1]=>
  array(5) {
    ["txt"]=>
    string(8) "Hey John"
    ["txt_id"]=>
    string(1) "5"
    ["name"]=>
    string(13) "Gilles Ragout"
    ["id_user"]=>
    string(1) "58"
    ["time"]=>
    string(19) "2017-12-15 08:37:21"
  }
 [2]=>
 array(5) {
   ["txt"]=>
   string(6) "What ?"
   ["txt_id"]=>
   string(2) "12"
   ["name"]=>
   string(11) "Noémie Nail"
   ["id_user"]=>
   string(1) "56"
   ["time"]=>
   string(19) "2017-05-10 05:12:36"
 }

So the result should be Messages1.csv and Messages2.csv because we have 2 differents txt_id.

And the output of the csv file should be for Messages1.csv :

txt            | time                | name
Hey              2017-12-15 08:28:47  John Doe
Hey John         2017-12-15 08:37:21  Gilles Ragout

And for Messages2.csv :

txt            | time                | name
What ?           2017-05-10 05:12:36   Noemie Nail

I try with this code.

$file = fopen('php://temp', 'w');
if (false === $file) {
    die('Failed to create temporary file');
}
foreach ($getUserConv as $conv) {
    fputcsv($file, array_keys($conv));
    fputcsv($file, $conv);
}
rewind($file);
$zip->addFromString(__('Conversations').'.csv', stream_get_contents($file));
fclose($file);

And the result of this code is a large csv file which contains all conversation but the column name is missing, and the headers is repeated.

For example I have Conversations which is generated and the output is :

txt | time
Hi    2017-12-18 01:01:10
txt | time
Yo    2017-12-18 02:10:08    

Try below code:

$messages = array(array('txt' => 'Hey', 'txt_id' => '5', 'name' => 'John Doe', 'id_user' => '5', 'time' => '2017-12-15 08:28:47'),
                      array('txt' => 'Hey John', 'txt_id' => '5', 'name' => 'Gilles Ragout', 'id_user' => '5', 'time' => '2017-12-15 08:37:21'),
                      array('txt' => 'What ?', 'txt_id' => '12', 'name' => 'Noemie Nail', 'id_user' => '56', 'time' => '2017-05-10 05:12:36'));
    echo '<br>messages=<pre>'. print_r($messages, true) .'</pre><br>';
    $csv_data = array();
    foreach($messages as $key => $value) {
        $csv_data[$value['txt_id']][] = array('txt' => $value['txt'], 'time' => $value['time'], 'name' => $value['name']);
    }
    unset($key, $value);

    if( is_array($csv_data) && count($csv_data) > 0 ) {
        foreach($csv_data as $index => $data) {
            if( is_array($data) && count($data) > 0 ) {
                $file = fopen('/tmp/Messages'. $index .'.csv', 'w');
                fputcsv($file, array_keys($data[0]));
                foreach($data as $key => $value) {
                    fputcsv($file, $value);
                }
                fclose($file);
                unset($key, $value, $file);
            }
        }
        unset($index, $data);
    }

str_getcsv - Manual, So for the default parameter values "" and \" have the same meaning. Other than [Ad group ID] => 22460178158 [Keyword ID] => You can parse your csv file into an associative array (by default) for each lines, or into an object. <?php PHP 5 is very well suited for reading in CSV files. With the file_get_contents() function, one can load the file contents in a string variable. Later, Explode () splits every file line into an array. Further, one needs to remove headers from the file using array_shift () function. This is then fed into str_getcsv().

all txt_id have different values in your shared csv data. Then how could you want only 2 csv files based on different txt_id?

Is it like, txt_id: 3 & 5 should go each time in Messages1.csv & other txt_id value details will go in Messages2.csv

fputcsv - Manual, fputcsv — Format line as CSV and write to file pointer as a fields array) as CSV and writes it (terminated by a newline) to the specified file handle . would be same as 't' because \ in that case would be only used for escaping but if you Secondly, if the first column heading / value of the CSV file begins with uppercase ID,  In this article we will see how we can create CSV file using PHP. We will also see how to automatically download the file instead of just showing it in the browser or giving the user a link to download it. Creating a CSV file using static data. If you want to store the data into a csv file, then you can use the code similar to the following

This is another example. It generates different file for different txt_id value. So, it is possible to have more than two files, if your txt_id values are more then two.

<?php
// Input values
$messages = array();
$messages[] = array(
    "txt"=>"Hey",
    "txt_id"=>"5",
    "name"=>"John Doe",
    "id_user"=>"1",
    "time"=>"2017-12-15 08:28:47"
);
$messages[] = array(
    "txt"=>"Hey John",
    "txt_id"=>"5",
    "name"=>"Gilles Ragout",
    "id_user"=>"1",
    "time"=>"2017-12-15 08:37:21"
);
$messages[] = array(
    "txt"=>"What ?",
    "txt_id"=>"12",
    "name"=>"Noémie Nail",
    "id_user"=>"56",
    "time"=>"2017-05-10 05:12:36"
);

// Delimiter and different id's. File creation and columns titles.
$delimiter = ',';
$ids = array();
foreach ($messages as $item) {
    $id = $item['txt_id'];
    if (!array_key_exists($id, $ids)) {
        $ids[$id] = $id;
        $file = fopen('messages'.$ids[$id].'.csv', "w");
        $line = array('txt', 'time', 'name');
        fputcsv($file, $line, $delimiter);
        fclose($file);
    }
}

// Data
foreach ($messages as $item) {
    $line = array($item['txt'], $item['time'], $item['name']);
    $id = array_search($item['txt_id'], $ids);
    $file = fopen('messages'.$ids[$id].'.csv', "a");
    fputcsv($file, $line, $delimiter);
    fclose($file);
}

// End
echo 'OK.';
?>

fgetcsv - Manual, PHP 5, PHP 7). fgetcsv — Gets line from file pointer and parse for CSV fields So for the default parameter values "" and \" have the same meaning. Other than array(3) { [0]=> string(13) "normal record" [1]=> string(19) "nothing to see here" [2]=> the file $data = fgetcsv($id, filesize($filename)); /*This will get us the */ Remove it with the following sentence set_magic_quotes_runtime(0) As this function is deprecated and it will be deleted in PHP 7.0, I recommend you to change your php.ini with the following sentencies: magic_quotes_gpc = Off magic_quotes_runtime = Off If you

PHP fputcsv() Function, The fputcsv() function formats a line as CSV and writes it to an open file. Tip: Also Specifies the open file to write to Specifies which array to get the data from. Loading CSV files into an array is something that comes up more times than I’d like to admit. Scrubbing mailing lists, loading flat files to a database and various other use cases are out there and fortunately, PHP makes it easy to to do. There are a few ways to

How to convert an array to CSV file in PHP ?, csv in the same directory where the program file is located. When you open this file with a CSV file reader application like Microsoft Excel you'll see the contents as  //parse a CSV file into a two-dimensional array //this seems as simple as splitting a string by lines and commas, but this only works if tricks are performed //to ensure that you do NOT split on lines and commas that are inside of double quotes.

How to Handle CSV with PHP: Read Write, Import Export, To check if the input file is with the proper CSV file extension and within the size limit. To check if the count of comma-separated values in all rows are same. records have same number of fields else { $lengthArray = array(); class="button​-row"> <input type="submit" id="btn-submit"  Note that fgetcsv, at least in PHP 5.3 or previous, will NOT work with UTF-16 encoded files. Your options are to convert the entire file to ISO-8859-1 (or latin1), or convert line by line and convert each line into ISO-8859-1 encoding, then use str_getcsv (or compatible backwards-compatible implementation).

Comments
  • What have you tried till now?
  • I update my post sorry.
  • Array 1 and 2 have the same txt_id. Typing error. My bad.
  • so do you want for each txt_id, a separate csv file should gets generated correct?
  • yes i want a separate csv file which is generated dynamically for each txt_id