使用PHP在CSV文件中用双引号括起每个字段?

时间:2022-09-15 15:11:52

I need to put all strings and number with double quotes in CSV file using PHP.

我需要使用PHP将所有字符串和数字用双引号放在CSV文件中。

How can I create CSV file from PHP in all data within double quotes ?

如何在双引号内的所有数据中从PHP创建CSV文件?

I am using this code to generate CSV - I am using codeigniter framework

我正在使用此代码生成CSV - 我正在使用codeigniter框架

$array = array(
    array(
     (string)'XXX XX XX',
     (string)'3',
     (string)'68878353',
     (string)'',
     (string)'xxxx@xxxx.xxx.xx',
    ),
);

$this->load->helper('csv');
array_to_csv($array, 'blueform.csv'); 

Output I am getting:

输出我得到:

"XXX XX XX",3,68878353,,xxxx@xxxx.xxx.xx

Expected Output:

预期产出:

"XXX XX XX","3","68878353","","xxxx@xxxx.xxx.xx"

Code of array_to_csv

array_to_csv的代码

if (!function_exists('array_to_csv')) {
    function array_to_csv($array, $download = "") {
        if ($download != "") {   
            header('Content-Type: application/csv');
            header('Content-Disposition: attachement; filename="' . $download . '"');
        }

        ob_start();
        $f = fopen('php://output', 'w') or show_error("Can't open php://output");
        $n = 0;
        foreach ($array as $line) {
            $n++;
            if (!fputcsv($f, $line)) {
                show_error("Can't write line $n: $line");
            }
        }
        fclose($f) or show_error("Can't close php://output");
        $str = ob_get_contents();
        ob_end_clean();

        if ($download == "") {
            return $str;
        } else {
            echo $str;
        }
    }
}

Thank you in advance

先谢谢你

10 个解决方案

#1


5  

When building a CSV in PHP, you should use the fputcsv function available from PHP 5

在PHP中构建CSV时,应使用PHP 5中提供的fputcsv函数

From the documentation, there's the following parameters:

从文档中,有以下参数:

int fputcsv ( resource $handle , array $fields [, string $delimiter = "," [, string $enclosure = '"' [, string $escape_char = "\" ]]] )

In that you have:

你有:

  • the file resource you're writing to
  • 您正在写入的文件资源
  • The data to put into the CSV
  • 要放入CSV的数据
  • The delimiter (the commas usually)
  • 分隔符(通常是逗号)
  • The string enclosure (this is the bit you want for your quotes)
  • 字符串外壳(这是你想要的引号)
  • Escape string (so if your data contains the enclosure character, you can escape it to avoid it looking like a new field)
  • 转义字符串(因此,如果您的数据包含机箱字符,则可以将其转义以避免它看起来像新字段)

As the defaults for that are , for the delimiter, and " for the enclosure, you'll not need to add more. That will correctly cover the strings. The numbers are a different matter. There's a work around on this SO question which I found after typing most of this and then having issues with numbers still :

因为默认设置是,对于分隔符,“对于机箱,你不需要添加更多。这将正确地覆盖字符串。数字是另一回事。有一个解决这个问题的问题,我在输入大部分内容后发现,然后仍然存在数字问题:

Not happy with this solution but it is what I did and worked. The idea is to set an empty char as enclosure character on fputcsv and add some quotes on every element of your array.

对这个解决方案不满意,但这是我做的和工作的。我们的想法是在fputcsv上设置一个空字符作为外壳字符,并在数组的每个元素上添加一些引号。

function encodeFunc($value) {
    return "\"$value\"";
}

fputcsv($handler, array_map(encodeFunc, $array), ',', chr(0));

#2


1  

I m using CSV helper here.

我在这里使用CSV帮助器。

For Generating result from db query for ex.

用于从db查询生成结果ex。

$sTable = "MY_TABLE_NAME";

$query = $this->db->get($sTable);

$this->load->helper('csv');

query_to_csv($query, TRUE, 'records.csv');

In CSV Helper onLine number 65 There is the code for query_to_csv.

在CSV Helper onLine编号65中有query_to_csv的代码。

here is csv_helper.php.

这是csv_helper.php。

I made a small edit there if you want everything with double inverted comma.

如果你想要所有的双重逗号,我在那里做了一个小编辑。

    <?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

// ------------------------------------------------------------------------

/**
 * CSV Helpers
 * Inspiration from PHP Cookbook by David Sklar and Adam Trachtenberg
 * 
 * @author      Jérôme Jaglale
 * @link        http://maestric.com/en/doc/php/codeigniter_csv
 */

// ------------------------------------------------------------------------

/**
 * Array to CSV
 *
 * download == "" -> return CSV string
 * download == "toto.csv" -> download file toto.csv
 */
if ( ! function_exists('array_to_csv'))
{
    function array_to_csv($array, $download = "")
    {
        if ($download != "")
        {   
            header('Content-Type: application/csv');
            header('Content-Disposition: attachement; filename="' . $download . '"');
        }       

        ob_start();
        $f = fopen('php://output', 'w') or show_error("Can't open php://output");
        $n = 0;     
        foreach ($array as $line)
        {
            $n++;
            if ( ! fputcsv($f, $line))
            {
                show_error("Can't write line $n: $line");
            }
        }
        fclose($f) or show_error("Can't close php://output");
        $str = ob_get_contents();
        ob_end_clean();

        if ($download == "")
        {
            return $str;    
        }
        else
        {   
            echo $str;
        }       
    }
}

// ------------------------------------------------------------------------

/**
 * Query to CSV
 *
 * download == "" -> return CSV string
 * download == "toto.csv" -> download file toto.csv
 */
if ( ! function_exists('query_to_csv'))
{
    function query_to_csv($query, $headers = TRUE, $download = "")
    {
        if ( ! is_object($query) OR ! method_exists($query, 'list_fields'))
        {
            show_error('invalid query');
        }

        $array = array();

        if ($headers)
        {
            $line = array();
            foreach ($query->list_fields() as $name)
            {
                $line[] = '"'.$name.'"';
            }
            $array[] = $line;
        }

        foreach ($query->result_array() as $row)
        {
            $line = array();
            foreach ($row as $item)
            {
                $line[] = '"'.$item.'"';
            }
            $array[] = $line;
        }

        echo array_to_csv($array, $download);
    }
}

/* End of file csv_helper.php */
/* Location: ./system/helpers/csv_helper.php */

This will give Insert double inverted comma in column name as well as rows. You can also remove "" this from column name.

这将为列名和行提供Insert双引号。您也可以从列名中删除“”。

使用PHP在CSV文件中用双引号括起每个字段?

#3


1  

Concat the string with this '"""';

Concat这个'“”“'的字符串;

Example: '"""' . {{String}} . '"""';

示例:'“”“'。{{String}}。'”“”';

This should work, it worked for me. This is a way to enclose the string.

这应该工作,它对我有用。这是一种封装字符串的方法。

#4


0  

Change your code little bit.

稍微改变你的代码。

fputcsv($f, $line)

To

fputcsv($f,array_map('strval', $line), ',', '"')

Hope this will help you.

希望这会帮助你。

FYI: its in array_to_csv

仅供参考:它在array_to_csv中

#5


0  

I would probably just replace fputcsv with a home grown version. Now I'm taking your data-structure to always be a grid like traditional spreadshees and CSV-files.

我可能只是用本土版本替换fputcsv。现在我把你的数据结构变成一个像传统的传播和CSV文件一样的网格。

function getQuotedString($arr){
    $buffer = "";
    foreach($arr as $line){
        $string = "";
        foreach($line as $data){
            // See if $string is no longer empty, meaning we need a comma to separate data
            if($string !== "") $string .= ',';
            $string .= '"' . $data . '"';
        }
        $buffer .= $string . PHP_EOL;
    }
    return $buffer;
}

Now use that in your code:

现在在你的代码中使用它:

...
ob_start();
$f = fopen('php://output', 'w') or show_error("Can't open php://output");
$quotedData = getQuotedString($arr);

for ($written = 0; $written < strlen($data); $written += $fwrite) {
    $fwrite = fwrite($f, substr($data, $written));
    if ($fwrite === false) {
        return $written;
    }
}

fclose($f) or show_error("Can't close php://output");
$str = ob_get_contents();
ob_end_clean();
...

You can then use $written to see how many bytes were written, or if you want to know how many lines there were you can just use sizeof($arr).

然后你可以使用$ written来查看写入了多少字节,或者如果你想知道有多少行,你可以使用sizeof($ arr)。

Hope this helps!

希望这可以帮助!

#6


0  

Wouldn't the implode function work beautifully for this?

内爆功能不会很好地为此工作吗?

$array = [ 
 (string)'XXX XX XX',
 (string)'3',
 (string)'68878353',
 (string)'',
 (string)'xxxx@xxxx.xxx.xx'
];
$csvData = '"' . implode('","', $array) . '"';

and then you can just write $csvData out to your file?

然后你可以写$ csvData到你的文件?

#7


0  

Ofcourse there are other ways to handle it, but by using fputcsv and works for most scenarios.

当然还有其他方法来处理它,但是通过使用fputcsv并适用于大多数场景。

if(!function_exists('array_to_csv')) {
    function array_to_csv($array, $download = "") {
        ob_start();
        $f = fopen('php://output', 'w') or die("Can't open php://output");
        $counter = count($array);
        for ($i = 0; $i < $counter; $i++) { 
            if(!fputcsv($f, array_map(function($value) {  return '"'.$value.'"';  }, $array[$i]), ",", "\"")) {
                die("Can't write line $i: ".print_r($array[$i], true));
            }
        }
        fclose($f) or die("Can't close php://output");
        $str = str_replace('"""', '"', ob_get_contents());
        ob_end_clean();

        if(strlen($download) > 0) {
            header('Content-Type: application/csv');
            header('Content-Disposition: attachment; filename="'.$download.'"');
            echo $str;
        } else {
            return $str;
        }
    }
}

#8


0  

Don't take the effort of properly enclosing every filed with double quotes. There are in-build php functions available to do the job without error.

不要用双引号正确地封闭每个字段。有内置的PHP函数可以正常工作而不会出错。

Not only double quotes, you will be in need for single quote ('), double quote ("), backslash (\) and NULL (the NULL byte).

不仅是双引号,还需要单引号('),双引号(“),反斜杠(\)和NULL(NULL字节)。

Use fputcsv() to write, and fgetcsv() to read, which will take care of all.

使用fputcsv()进行写入,使用fgetcsv()进行读取,这将完成所有操作。

#9


0  

You could use the implode() function to make the code above even more simple:

您可以使用implode()函数使上面的代码更加简单:

$delimiter = ';';
$enclosure = '"';
$linefeed  = "\n";

$lines = array();
// traversing data, one row at a time
foreach ($data as $row) {
    $arr = array();
    // traversing row, col after col
    foreach ($row as $col => $val) {
        // MySQL-style escaping double quotes
        $val = str_replace('"','""',$val);
        // wrapping each value in double quotes
        $arr[] = sprintf('%s%s%s',$enclosure,$val,$enclosure);
    }
    // generating formatted line and storing it
    $lines[] = implode($delimiter,$arr);
}
// join each lines to have the final output
$output = implode($linefeed,$lines);
echo $output;

#10


-1  

I have got solution this function convert multi dimension array into CSV with double quote and

我有解决方案这个功能将多维数组转换为CSV双引号和

function arr_to_csv($arr)
  {
        $filePointer="export.csv";
        $delimiter=",";
        $enclosure='"';
        $dataArray =$arr;

        $string = "";

        // No leading delimiter
        $writeDelimiter = FALSE;
        //foreach($dataArray as $dataElement)
        foreach ($dataArray as $key1 => $value){
        foreach ($value as $key => $dataElement) 

         {
          // Replaces a double quote with two double quotes
          $dataElement=str_replace("\"", "\"\"", $dataElement);
          // Adds a delimiter before each field (except the first)
          // Encloses each field with $enclosure and adds it to the string
          if($writeDelimiter) $string .= $delimiter;
          // $new_string = $enclosure . $dataElement . $enclosure;
          $string .= $enclosure . $dataElement . $enclosure;
         // Delimiters are used every time except the first.
          $writeDelimiter = TRUE;
         } // end foreach($dataArray as $dataElement)

                $string .= "\n";

         }      
        // Append new line
        $string .= "\n";    
         //$string = "An infinite number of monkeys";
        print($newstring);
       // Write the string to the file
      // fwrite($filePointer,$string);
       header('Content-Type: application/csv');
      header('Content-Disposition: attachment; filename="'.$filePointer.'";');
  }

#1


5  

When building a CSV in PHP, you should use the fputcsv function available from PHP 5

在PHP中构建CSV时,应使用PHP 5中提供的fputcsv函数

From the documentation, there's the following parameters:

从文档中,有以下参数:

int fputcsv ( resource $handle , array $fields [, string $delimiter = "," [, string $enclosure = '"' [, string $escape_char = "\" ]]] )

In that you have:

你有:

  • the file resource you're writing to
  • 您正在写入的文件资源
  • The data to put into the CSV
  • 要放入CSV的数据
  • The delimiter (the commas usually)
  • 分隔符(通常是逗号)
  • The string enclosure (this is the bit you want for your quotes)
  • 字符串外壳(这是你想要的引号)
  • Escape string (so if your data contains the enclosure character, you can escape it to avoid it looking like a new field)
  • 转义字符串(因此,如果您的数据包含机箱字符,则可以将其转义以避免它看起来像新字段)

As the defaults for that are , for the delimiter, and " for the enclosure, you'll not need to add more. That will correctly cover the strings. The numbers are a different matter. There's a work around on this SO question which I found after typing most of this and then having issues with numbers still :

因为默认设置是,对于分隔符,“对于机箱,你不需要添加更多。这将正确地覆盖字符串。数字是另一回事。有一个解决这个问题的问题,我在输入大部分内容后发现,然后仍然存在数字问题:

Not happy with this solution but it is what I did and worked. The idea is to set an empty char as enclosure character on fputcsv and add some quotes on every element of your array.

对这个解决方案不满意,但这是我做的和工作的。我们的想法是在fputcsv上设置一个空字符作为外壳字符,并在数组的每个元素上添加一些引号。

function encodeFunc($value) {
    return "\"$value\"";
}

fputcsv($handler, array_map(encodeFunc, $array), ',', chr(0));

#2


1  

I m using CSV helper here.

我在这里使用CSV帮助器。

For Generating result from db query for ex.

用于从db查询生成结果ex。

$sTable = "MY_TABLE_NAME";

$query = $this->db->get($sTable);

$this->load->helper('csv');

query_to_csv($query, TRUE, 'records.csv');

In CSV Helper onLine number 65 There is the code for query_to_csv.

在CSV Helper onLine编号65中有query_to_csv的代码。

here is csv_helper.php.

这是csv_helper.php。

I made a small edit there if you want everything with double inverted comma.

如果你想要所有的双重逗号,我在那里做了一个小编辑。

    <?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

// ------------------------------------------------------------------------

/**
 * CSV Helpers
 * Inspiration from PHP Cookbook by David Sklar and Adam Trachtenberg
 * 
 * @author      Jérôme Jaglale
 * @link        http://maestric.com/en/doc/php/codeigniter_csv
 */

// ------------------------------------------------------------------------

/**
 * Array to CSV
 *
 * download == "" -> return CSV string
 * download == "toto.csv" -> download file toto.csv
 */
if ( ! function_exists('array_to_csv'))
{
    function array_to_csv($array, $download = "")
    {
        if ($download != "")
        {   
            header('Content-Type: application/csv');
            header('Content-Disposition: attachement; filename="' . $download . '"');
        }       

        ob_start();
        $f = fopen('php://output', 'w') or show_error("Can't open php://output");
        $n = 0;     
        foreach ($array as $line)
        {
            $n++;
            if ( ! fputcsv($f, $line))
            {
                show_error("Can't write line $n: $line");
            }
        }
        fclose($f) or show_error("Can't close php://output");
        $str = ob_get_contents();
        ob_end_clean();

        if ($download == "")
        {
            return $str;    
        }
        else
        {   
            echo $str;
        }       
    }
}

// ------------------------------------------------------------------------

/**
 * Query to CSV
 *
 * download == "" -> return CSV string
 * download == "toto.csv" -> download file toto.csv
 */
if ( ! function_exists('query_to_csv'))
{
    function query_to_csv($query, $headers = TRUE, $download = "")
    {
        if ( ! is_object($query) OR ! method_exists($query, 'list_fields'))
        {
            show_error('invalid query');
        }

        $array = array();

        if ($headers)
        {
            $line = array();
            foreach ($query->list_fields() as $name)
            {
                $line[] = '"'.$name.'"';
            }
            $array[] = $line;
        }

        foreach ($query->result_array() as $row)
        {
            $line = array();
            foreach ($row as $item)
            {
                $line[] = '"'.$item.'"';
            }
            $array[] = $line;
        }

        echo array_to_csv($array, $download);
    }
}

/* End of file csv_helper.php */
/* Location: ./system/helpers/csv_helper.php */

This will give Insert double inverted comma in column name as well as rows. You can also remove "" this from column name.

这将为列名和行提供Insert双引号。您也可以从列名中删除“”。

使用PHP在CSV文件中用双引号括起每个字段?

#3


1  

Concat the string with this '"""';

Concat这个'“”“'的字符串;

Example: '"""' . {{String}} . '"""';

示例:'“”“'。{{String}}。'”“”';

This should work, it worked for me. This is a way to enclose the string.

这应该工作,它对我有用。这是一种封装字符串的方法。

#4


0  

Change your code little bit.

稍微改变你的代码。

fputcsv($f, $line)

To

fputcsv($f,array_map('strval', $line), ',', '"')

Hope this will help you.

希望这会帮助你。

FYI: its in array_to_csv

仅供参考:它在array_to_csv中

#5


0  

I would probably just replace fputcsv with a home grown version. Now I'm taking your data-structure to always be a grid like traditional spreadshees and CSV-files.

我可能只是用本土版本替换fputcsv。现在我把你的数据结构变成一个像传统的传播和CSV文件一样的网格。

function getQuotedString($arr){
    $buffer = "";
    foreach($arr as $line){
        $string = "";
        foreach($line as $data){
            // See if $string is no longer empty, meaning we need a comma to separate data
            if($string !== "") $string .= ',';
            $string .= '"' . $data . '"';
        }
        $buffer .= $string . PHP_EOL;
    }
    return $buffer;
}

Now use that in your code:

现在在你的代码中使用它:

...
ob_start();
$f = fopen('php://output', 'w') or show_error("Can't open php://output");
$quotedData = getQuotedString($arr);

for ($written = 0; $written < strlen($data); $written += $fwrite) {
    $fwrite = fwrite($f, substr($data, $written));
    if ($fwrite === false) {
        return $written;
    }
}

fclose($f) or show_error("Can't close php://output");
$str = ob_get_contents();
ob_end_clean();
...

You can then use $written to see how many bytes were written, or if you want to know how many lines there were you can just use sizeof($arr).

然后你可以使用$ written来查看写入了多少字节,或者如果你想知道有多少行,你可以使用sizeof($ arr)。

Hope this helps!

希望这可以帮助!

#6


0  

Wouldn't the implode function work beautifully for this?

内爆功能不会很好地为此工作吗?

$array = [ 
 (string)'XXX XX XX',
 (string)'3',
 (string)'68878353',
 (string)'',
 (string)'xxxx@xxxx.xxx.xx'
];
$csvData = '"' . implode('","', $array) . '"';

and then you can just write $csvData out to your file?

然后你可以写$ csvData到你的文件?

#7


0  

Ofcourse there are other ways to handle it, but by using fputcsv and works for most scenarios.

当然还有其他方法来处理它,但是通过使用fputcsv并适用于大多数场景。

if(!function_exists('array_to_csv')) {
    function array_to_csv($array, $download = "") {
        ob_start();
        $f = fopen('php://output', 'w') or die("Can't open php://output");
        $counter = count($array);
        for ($i = 0; $i < $counter; $i++) { 
            if(!fputcsv($f, array_map(function($value) {  return '"'.$value.'"';  }, $array[$i]), ",", "\"")) {
                die("Can't write line $i: ".print_r($array[$i], true));
            }
        }
        fclose($f) or die("Can't close php://output");
        $str = str_replace('"""', '"', ob_get_contents());
        ob_end_clean();

        if(strlen($download) > 0) {
            header('Content-Type: application/csv');
            header('Content-Disposition: attachment; filename="'.$download.'"');
            echo $str;
        } else {
            return $str;
        }
    }
}

#8


0  

Don't take the effort of properly enclosing every filed with double quotes. There are in-build php functions available to do the job without error.

不要用双引号正确地封闭每个字段。有内置的PHP函数可以正常工作而不会出错。

Not only double quotes, you will be in need for single quote ('), double quote ("), backslash (\) and NULL (the NULL byte).

不仅是双引号,还需要单引号('),双引号(“),反斜杠(\)和NULL(NULL字节)。

Use fputcsv() to write, and fgetcsv() to read, which will take care of all.

使用fputcsv()进行写入,使用fgetcsv()进行读取,这将完成所有操作。

#9


0  

You could use the implode() function to make the code above even more simple:

您可以使用implode()函数使上面的代码更加简单:

$delimiter = ';';
$enclosure = '"';
$linefeed  = "\n";

$lines = array();
// traversing data, one row at a time
foreach ($data as $row) {
    $arr = array();
    // traversing row, col after col
    foreach ($row as $col => $val) {
        // MySQL-style escaping double quotes
        $val = str_replace('"','""',$val);
        // wrapping each value in double quotes
        $arr[] = sprintf('%s%s%s',$enclosure,$val,$enclosure);
    }
    // generating formatted line and storing it
    $lines[] = implode($delimiter,$arr);
}
// join each lines to have the final output
$output = implode($linefeed,$lines);
echo $output;

#10


-1  

I have got solution this function convert multi dimension array into CSV with double quote and

我有解决方案这个功能将多维数组转换为CSV双引号和

function arr_to_csv($arr)
  {
        $filePointer="export.csv";
        $delimiter=",";
        $enclosure='"';
        $dataArray =$arr;

        $string = "";

        // No leading delimiter
        $writeDelimiter = FALSE;
        //foreach($dataArray as $dataElement)
        foreach ($dataArray as $key1 => $value){
        foreach ($value as $key => $dataElement) 

         {
          // Replaces a double quote with two double quotes
          $dataElement=str_replace("\"", "\"\"", $dataElement);
          // Adds a delimiter before each field (except the first)
          // Encloses each field with $enclosure and adds it to the string
          if($writeDelimiter) $string .= $delimiter;
          // $new_string = $enclosure . $dataElement . $enclosure;
          $string .= $enclosure . $dataElement . $enclosure;
         // Delimiters are used every time except the first.
          $writeDelimiter = TRUE;
         } // end foreach($dataArray as $dataElement)

                $string .= "\n";

         }      
        // Append new line
        $string .= "\n";    
         //$string = "An infinite number of monkeys";
        print($newstring);
       // Write the string to the file
      // fwrite($filePointer,$string);
       header('Content-Type: application/csv');
      header('Content-Disposition: attachment; filename="'.$filePointer.'";');
  }