Convert php array to csv string

后端 未结 8 1390
一向
一向 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: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; 
    }
    

提交回复
热议问题