Convert php array to csv string

I have several ways to convert a php array to a csv string from both stackoverflow and google. But I have problems, if I want to save a mobile phone number, such as 01727499452, it saves as without the first value 0. Currently I use this piece of code: Converting an array to csv

Can anybody help me.

Array [1] => Array ( [0] => Lalu ' " ; \\ Kumar [1] => Mondal [2] => 01934298345 [3] => ) [2] => Array ( [0] => Pritom [1] => Kumar Mondal [2] => 01727499452 [3] => Bit Mascot ) [3] => Array ( [0] => Pritom [1] => Kumar Mondal [2] => 01711511149 [3] => ) [4] => Array ( [0] => Raaz [1] => Mukherzee [2] => 01911224589 [3] => Khulna University 06 ) 

)

My code block:

 function arrayToCsv( array $fields, $delimiter = ';', $enclosure = '"', $encloseAll = false, $nullToMysqlNull = false ) { $delimiter_esc = preg_quote($delimiter, '/'); $enclosure_esc = preg_quote($enclosure, '/'); $outputString = ""; foreach($fields as $tempFields) { $output = array(); foreach ( $tempFields as $field ) { if ($field === null && $nullToMysqlNull) { $output[] = 'NULL'; continue; } // Enclose fields containing $delimiter, $enclosure or whitespace if ( $encloseAll || preg_match( "/(?:${delimiter_esc}|${enclosure_esc}|\s)/", $field ) ) { $field = $enclosure . str_replace($enclosure, $enclosure . $enclosure, $field) . $enclosure; } $output[] = $field." "; } $outputString .= implode( $delimiter, $output )."\r\n"; } return $outputString; } 

Thanks,

Pritom.

+11
php phone-number multidimensional-array csv
source share
7 answers

You can use the str_putcsv function:

 if(!function_exists('str_putcsv')) { function str_putcsv($input, $delimiter = ',', $enclosure = '"') { // Open a memory "file" for read/write... $fp = fopen('php://temp', 'r+'); // ... write the $input array to the "file" using fputcsv()... fputcsv($fp, $input, $delimiter, $enclosure); // ... rewind the "file" so we can read what we just wrote... rewind($fp); // ... read the entire line into a variable... $data = fread($fp, 1048576); // ... close the "file"... fclose($fp); // ... and return the $data to the caller, with the trailing newline from fgets() removed. return rtrim($data, "\n"); } } $csvString = ''; foreach ($list as $fields) { $csvString .= str_putcsv($fields); } 

Learn more about this on GitHub , a feature created by @johanmeiring.

+21
source share

That's what you need?

 $out = ""; foreach($array as $arr) { $out .= implode(",", $arr) . "\r\n"; } 

It goes through your array, creating a new line in each loop, dividing the array values ​​by ",".

+18
source share

Are you sure that the numbers are actually stored without a leading zero? Have you looked at the actual CSV result in a text editor?

If you just opened the CSV file in a spreadsheet application, it is most likely a spreadsheet that interprets your phone numbers as numerical values ​​and discards zeros when they are displayed. You can usually fix this in a spreadsheet by changing the formatting options in that particular column.

+2
source share

Since this is a CSV, not something like JSON, everything will read as a string anyway, so just convert your number to a string with:

  • (string)$variable
  • strval($variable) (which I would prefer here)
  • combine with an empty string, for example $variable . '' $variable . ''

PHP gettype() will also be an option. You can enter each field into a string (even if it is already one) using one of the described methods or you can only call a field with a number after which it does this:

 if (gettype($field) == 'integer' || gettype($field) == 'double') { $field = strval($field); // Change $field to string if it a numeric type } 

Here is the full code added with it

 function arrayToCsv( array $fields, $delimiter = ';', $enclosure = '"', $encloseAll = false, $nullToMysqlNull = false ) { $delimiter_esc = preg_quote($delimiter, '/'); $enclosure_esc = preg_quote($enclosure, '/'); $outputString = ""; foreach($fields as $tempFields) { $output = array(); foreach ( $tempFields as $field ) { // ADDITIONS BEGIN HERE if (gettype($field) == 'integer' || gettype($field) == 'double') { $field = strval($field); // Change $field to string if it a numeric type } // ADDITIONS END HERE if ($field === null && $nullToMysqlNull) { $output[] = 'NULL'; continue; } // Enclose fields containing $delimiter, $enclosure or whitespace if ( $encloseAll || preg_match( "/(?:${delimiter_esc}|${enclosure_esc}|\s)/", $field ) ) { $field = $enclosure . str_replace($enclosure, $enclosure . $enclosure, $field) . $enclosure; } $output[] = $field." "; } $outputString .= implode( $delimiter, $output )."\r\n"; } return $outputString; } 
0
source share

I use this function to convert php array to csv. It also works for a multidimensional array.

 public function array_2_csv($array) { $csv = array(); foreach ($array as $item=>$val) { if (is_array($val)) { $csv[] = $this->array_2_csv($val); $csv[] = "\n"; } else { $csv[] = $val; } } return implode(';', $csv); } 
0
source share

The above function is not entirely correct, because it considers \ n as an element, and this is not what we need, since each line should be separated only \ n. Thus, a more efficient code would be:

 function array2csv($array, $delimiter = "\n") { $csv = array(); foreach ($array as $item=>$val) { if (is_array($val)) { $csv[] = $this->array2csv($val, ";"); } else { $csv[] = $val; } } return implode($delimiter, $csv); } 
0
source share

Here is a slightly more general purpose solution. I was actually looking for a way to make row lists for bulk SQL inserts. The code will look like this:

 foreach ($rows as $row) { $string = toDelimitedString($row); // Now append it to a file, add line break, whatever the need may be } 

And here is a useful function that I added to my takeit:

 /** * Convert an array of strings to a delimited string. This function supports CSV as well as SQL output since * the quote character is customisable and the escaping behaviour is the same for CSV and SQL. * * Tests: * echo toDelimitedString([], ',', '\'', true) . "\n"; * echo toDelimitedString(['A'], ',', '\'', true) . "\n"; * echo toDelimitedString(['A', 'B'], ',', '\'', true) . "\n"; * echo toDelimitedString(['A', 'B\'C'], ',', '\'', true) . "\n"; * echo toDelimitedString([], ',', '\'', true) . "\n"; * echo toDelimitedString(['A'], ',', '"', true) . "\n"; * echo toDelimitedString(['A', 'B'], ',', '"', true) . "\n"; * echo toDelimitedString(['A', 'B"C'], ',', '"', true) . "\n"; * * Outputs: * <Empty String> * 'A' * 'A','B' * 'A','B''C' * <Empty String> * "A" * "A","B" * "A","B""C" * * @param array $array A one-dimensional array of string literals * @param string $delimiter The character to separate string parts * @param string $quoteChar The optional quote character to surround strings with * @param bool $escape Flag to indicate whether instances of the quote character should be escaped * @return string */ function toDelimitedString(array $array, string $delimiter = ',', string $quoteChar = '"', bool $escape = true) { // Escape the quote character, since it is somewhat expensive it can be suppressed if ($escape && !empty($quoteChar)) { $array = str_replace($quoteChar, $quoteChar . $quoteChar, $array); } // Put quotes and commas between all the values $values = implode($array, $quoteChar . $delimiter . $quoteChar); // Put first and last quote around the list, but only if it is not empty if (strlen($values) > 0) { $values = $quoteChar . $values . $quoteChar; } return $values; } 
0
source share

All Articles