Convert php array to csv string

fputcsv array to string conversion
php str_putcsv
php csv header row
php csv library
php get first row of csv file
php array to string
fputcsv new line
laravel csv to array

I have several method to transform php array to csv string both from stackoverflow and google. But I am in trouble that if I want to store mobile number such as 01727499452, it saves as without first 0 value. I am currently using this piece of code: Convert array into csv

Can anyone please 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.

You could use 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);
 }

More about this on GitHub, a function created by @johanmeiring.

Convert php array to csv string, You could use str_putcsv function: if(!function_exists('str_putcsv')) { function str_putcsv($input, $delimiter = ',', $enclosure = '"') { // Open a  PHP array to CSV FAQ: How do your convert a PHP array to a CSV string? Converting a PHP array to a PHP CSV string is so easy, it actually felt like I trick question when I just found the answer in the PHP docs.

Is this what you need?

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

}

It runs trough your array creating a new line on each loop seperating the array values with a ",".

str_getcsv - Manual, Parses a string input for fields in CSV format and returns an array containing the Here is a quick and easy way to convert a CSV file to an associated array: To convert an array into a CSV file we can use fputcsv() function. The fputcsv() function is used to format a line as CSV (comma separated values) file and writes it to an open file.

Are you sure the numbers are actually being saved without the leading zero? Have you looked at the actual CSV output in a text editor?

If you've just opened up the CSV file in a spreadsheet application, it is most likely the spreadsheet that is interpreting your telephone numbers as numeric values and dropping the zeros when displaying them. You can usually fix that in the spreadsheet by changing the formatting options on that particular column.

fputcsv - Manual, fputcsv() formats a line (passed as a fields array) as CSV and writes it (terminated Returns the length of the written string or FALSE on failure. the solution for how to solve the encoding problem while converting an array to csv file is below. Converting CSV to array. I need to convert that file into a php array. This is my code so far: Sort array of objects by string property value. 3078.

A PHP array to CSV string example, Converting a PHP array to a PHP CSV string is so easy, it actually felt like I trick question when I just found the answer in the PHP docs. We decoded the JSON string into an associative PHP array. We gave our CSV file a name. In this case, it is example.csv; We opened a writable file pointer using the fopen function. This file pointer allows us to write data to a particular file. We loop through our associative array, which contains our decoded JSON data.

I'm using this function to convert php array to csv. It's working also for 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);
}

How to create comma separated list from an array in PHP , an array in PHP ? The comma separated list can be created by using implode() function. It will return the joined string formed from the elements of array. Example 1: How to convert list of elements in an array using jQuery ? How to create  How to convert items in array to a comma separated string in PHP? This is a bad idea if you're trying to create reliable CSV strings. How to convert array

How to convert an array to CSV file in PHP ?, How to convert an array to CSV file in PHP ? To convert an array into a CSV file we can use fputcsv() function. The fputcsv() function is used to format a line as CSV (comma separated values) file and writes it to an open file. It's a simple question; I am a newbie in C#, how can I perform the following. I want to convert an array of integers to a comma-separated string.

Generate CSV from Array, $handle = fopen('php://temp', 'r+'); foreach ($data as $line) { fputcsv($handle, $data = array( array(1, 2, 4), array('test string', 'test, literal, comma', 'test literal  How do I convert an array object to a string in PowerShell? Ask Question Asked 8 years, 6 months ago. Active 1 month ago. Viewed 463k times 169. 31. How can I convert

How to Handle CSV with PHP: Read Write, Import Export, CSV file format and MIME type; How to convert PHP Array to CSV? structure and data are extracted and prepared in the form of CSV string. Inspired by boonerunner's function, I wrote a smaller, faster, and more flexible one, which also uses less memory. I also renamed it to avoid collision or overwriting the PHP function, and gave the 3rd and 4th parameter default values like fputcsv() uses.

Comments
  • That's the problem with using other people's wheels.
  • Save it as a string. I'd recommend that for phone numbers anyway, because you're just going to want to save that + as well ;)
  • You should be using PHP's built in CSV functions like php.net/manual/en/function.fputcsv.php
  • Some second-hand advice: If you're not going to do arithmetic on it, store it as a string. The Daily WTF contains examples of many a phone number printed in scientific notation, which ultimately stems from someone storing it as an integer.
  • The number will be stored correctly in the CSV, with a leading zero; but when opened in MS Excel, then Excel will reformat it - either use a file format that supports format information already (not CSV) so that Excel doesn't apply its standard behaviour, or force it to be a formula string when saving ="01911224589"
  • It's a minor thing but i think you meant $csvString .= str_putcsv($fp, $fields);. Missing the $ ;)
  • shouldn't it be str_putcsv($fields); instead of str_putcsv($fp, $fields);
  • I liked this solution. I made one small modification when I "borrowed" it: ... $len = ftell($fp)+1; rewind($fp); $data = fread($fp,$len); ... and it seems to work. I didn't know what 1048576 represents, so I didn't want to use it directly.
  • Is this what I want? Please read my question and if you are not clear please ask me.
  • It should be, i dont see why you wouldnt:) Give it a shot, and see if it meets your expectations.
  • I have used something similar in a number of situations, and it works well with a warning (or two). This breaks if some value in $arr has a ',' character in it. The csv format has ways to handle it that aren't being addressed addressed by this solution. Also, you are coding a Windows specific newline with "\r\n", which may cause problems in some situations. Using the constant PHP_EOL will result in more portable code.
  • OP should maybe try to examine the contents of $out