将php数组转换为csv字符串



我有几个方法转换php数组csv字符串都从stackoverflow和谷歌。但我遇到了麻烦,如果我想存储手机号码,如01727499452,它保存为没有第一个0值。我目前正在使用这段代码:将数组转换为csv

有谁能帮帮我吗?

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
    )

)

我的代码块:

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 )."rn";
}
return $outputString; }

谢谢,

Pritom .

您可以使用str_putcsv函数:

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);
 }

关于GitHub的更多信息,一个由@johanmeiring创建的函数。

这就是你需要的

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

它在你的数组中运行,在每个循环中创建一个新的行,用","分隔数组值

灵感来自@alexcristea的回答:

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', 'dddd'),
    array('123', '456', '789'),
    array('"aaa"', '"bbb"')
);
var_dump(array2csv($list));

您确定实际保存的数字没有前导零吗?您看过文本编辑器中实际的CSV输出吗?

如果您刚刚在电子表格应用程序中打开CSV文件,那么很可能电子表格将您的电话号码解释为数值并在显示它们时删除零。您通常可以在电子表格中通过更改特定列上的格式选项来解决这个问题。

因为它是CSV而不是JSON,所以所有内容都将被读取为字符串所以只需将数字转换为字符串,使用:

  • (string)$variable
  • strval($variable)(我更喜欢这里)
  • 与空字符串连接,如$variable . ''

PHP的gettype()也是一个选项。您可以使用我描述的方法之一将每个字段类型转换为字符串(即使它已经是一个字符串),或者您可以通过调用后面的数字字段:

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

下面是添加了

的完整代码
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 )."rn";
    }
    return $outputString; 
}

这里有一个更通用的解决方案。实际上,我正在寻找一种方法来为SQL批量插入制作字符串列表。代码看起来像这样:

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

下面是我最后添加到工具包中的有用函数:

/**
 * 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;
}

这对我来说很有效,它依赖于PHP内置的CSV函数。它的绝妙之处在于,它会自动正确地在相关字段周围添加倒逗号。

// Create an array of elements
$list = array(
    ['Name', 'age', 'Gender'],
    ['Bob', 20, 'Male'],
    ['John', 25, 'Male'],
    ['Jessica', 30, 'Female']
);
// Create an output buffer
$outputBuffer = fopen('php://temp', 'w');
// Loop through the array and write to the output buffer
foreach ($list as $fields) {
    fputcsv($outputBuffer, $fields);
}
// Rewind the output buffer
rewind($outputBuffer);
// Read the contents of the output buffer
$csvString = stream_get_contents($outputBuffer);
// Close the output buffer
fclose($outputBuffer);
// Output the CSV string
echo $csvString;

此实现不使用文件指针,不应该无意中修改传递给它的任何数据,并且只在需要时进行转义,类似于fputcsv()(但没有$escape_char的无意义):

function str_putcsv(array $fields, string $delimiter = ',', string $enclosure = '"') {
    $escs = [];
    foreach ($fields as $field) {
        $esc = (string) $field;
        if (
            false !== strpos($esc, $delimiter)
            || false !== strpos($esc, $enclosure)
        ) {
            $esc = $enclosure . strtr($esc, ["$enclosure" => "$enclosure$enclosure"]) . $enclosure;
        }
        $escs[] = $esc;
    }
    return implode($delimiter, $escs) . PHP_EOL;
}

如果您的PHP版本不支持string类型声明,请删除它们

我使用这个函数将php数组转换为csv。它也适用于多维数组。

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);
}

上面的函数不完全正确,因为它认为n是一个元素,这不是我们想要的,因为每行只能用n分隔。所以更有效的代码应该是:

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);
}

相关内容

  • 没有找到相关文章

最新更新