Convert php array to csv string

后端 未结 8 1278
一向
一向 2020-12-10 02:47

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,

相关标签:
8条回答
  • 2020-12-10 03:08

    This is what you need

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

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

    0 讨论(0)
  • 2020-12-10 03:11

    Here is a solution that is a little more general purpose. I was actually looking for a way to make string lists for SQL bulk inserts. The code would 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 the useful function that I ended up adding to my tookit:

    /**
     * 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 讨论(0)
  • 2020-12-10 03:12

    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.

    0 讨论(0)
  • 2020-12-10 03:12

    Inspired by @alexcristea's answer:

    function array2csv($data, $delimiter = ',', $enclosure = '"', $escape_char = "\\")
    {
        $f = fopen('php://memory', 'r+');
        foreach ($data as $item) {
            fputcsv($f, $item, $delimiter, $enclosure, $escape_char);
        }
        rewind($f);
        return stream_get_contents($f);
    }
    
    $list = array (
        array('aaa', 'bbb', 'ccc', 'ffffdd'),
        array('123', '456', '789'),
        array('"aaa"', '"bbb"')
    );
    var_dump(array2csv($list));
    
    0 讨论(0)
  • 2020-12-10 03:17

    Since it's a CSV and not something like JSON, everything is going to be read as a string anyway so just convert your number to a string with:

    • (string)$variable
    • strval($variable) (which I would prefer here)
    • concatenate with an empty string like $variable . ''

    PHP's gettype() would also be an option. You can type cast every field to a string (even if it already is one) by using one of the methods I described or you can call out just the number field you're after by doing this:

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

    Here's the full code with it added

    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's 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 讨论(0)
  • 2020-12-10 03:17

    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);
    }
    
    0 讨论(0)
提交回复
热议问题