Home Backend Development PHP Tutorial PHP exports csv files: specify encoding export and csv file import and export classes

PHP exports csv files: specify encoding export and csv file import and export classes

Jul 25, 2016 am 08:51 AM

  1. /*
  2. * PHP code to export MySQL data to CSV
  3. *
  4. * Sends the result of a MySQL query as a CSV file for download
  5. * Easy to convert to UTF-8.
  6. */
  7. /*
  8. * establish database connection
  9. */
  10. $conn = mysql_connect('localhost', 'login', 'pass') or die(mysql_error());
  11. mysql_select_db('database_name', $conn) or die(mysql_error($conn));
  12. mysql_query("SET NAMES CP1252");
  13. /*
  14. * execute sql query
  15. */
  16. $query = sprintf('SELECT field1,field2 FROM table_name');
  17. $result = mysql_query($query, $conn) or die(mysql_error($conn));
  18. /*
  19. * send response headers to the browser
  20. * following headers instruct the browser to treat the data as a csv file called export.csv
  21. */
  22. header('Content-Type: text/csv; charset=cp1252');
  23. header('Content-Disposition: attachment;filename=output.csv');
  24. /*
  25. * output header row (if atleast one row exists)
  26. */
  27. $row = mysql_fetch_assoc($result);
  28. if ($row) {
  29. echocsv(array_keys($row));
  30. }
  31. /*
  32. * output data rows (if atleast one row exists)
  33. */ 导出csv文件
  34. while ($row) {
  35. echocsv($row);
  36. $row = mysql_fetch_assoc($result);
  37. }
  38. /*
  39. * echo the input array as csv data maintaining consistency with most CSV implementations
  40. * - uses double-quotes as enclosure when necessary
  41. * - uses double double-quotes to escape double-quotes
  42. * - uses CRLF as a line separator
  43. */
  44. function echocsv($fields)
  45. {
  46. $separator = '';
  47. foreach ($fields as $field) {
  48. if (preg_match('/\r|\n|,|"/', $field)) {
  49. $field = '"' . str_replace('"', '""', $field) . '"';
  50. }
  51. echo $separator . $field;
  52. $separator = ',';
  53. }
  54. echo "rn";
  55. }
  56. ?>
复制代码

2. PHP import and export csv file classes

php implements the import and export classes of csv files. Code:

  1. /**
  2. *CSV file processing class
  3. */
  4. class Csv{
  5. public $csv_array; //csv array data
  6. public $csv_str; //csv file data
  7. public function __construct($param_arr , $column){
  8. $this->csv_array = $param_arr;
  9. $this->path = $path;
  10. $this->column = $column;
  11. }
  12. /**
  13. * Export
  14. **/
  15. public function export(){
  16. if(empty($this->csv_array) || empty($this->column)){
  17. return false;
  18. }
  19. $param_arr = $this->csv_array;
  20. unset ($this->csv_array);
  21. $export_str = implode(',',$param_arr['nav'])."n";
  22. unset($param_arr['nav']);
  23. //Assemble data
  24. foreach($param_arr as $k=>$v){
  25. foreach($v as $k1=>$v1){
  26. $export_str .= implode(',',$v1)."n";
  27. }
  28. }
  29. //Export $export_str
  30. header( "Cache-Control: public" );
  31. header( "Pragma: public" );
  32. header("Content-type:application/vnd.ms-excel");
  33. header("Content-Disposition:attachment;filename=txxx.csv");
  34. header('Content-Type:APPLICATION/OCTET-STREAM');
  35. ob_start();
  36. // $file_str= iconv("utf-8 ",'gbk',$export_str);
  37. ob_end_clean();
  38. echo $export_str;
  39. }
  40. /**
  41. * Import
  42. **/
  43. public function import($path,$column = 3){
  44. $flag = flase ;
  45. $code = 0;
  46. $msg = 'Unprocessed';
  47. $filesize = 1; //1MB
  48. $maxsize = $filesize * 1024 * 1024;
  49. $max_column = 1000;
  50. //Detect whether the file exists
  51. if($flag === flase){
  52. if(!file_exists($path)){
  53. $msg = 'File does not exist';
  54. $flag = true;
  55. }
  56. }
  57. //Detect file format
  58. if ($flag === flase){
  59. $ext = preg_replace("/.*.([^.]+)/","$1",$path);
  60. if($ext != 'csv'){
  61. $msg = 'Only CSV format files can be imported';
  62. $flag = true;
  63. }
  64. }
  65. //Detect file size
  66. if($flag === flase){
  67. if(filesize($path)> $maxsize){
  68. $msg = 'The imported file must not exceed'.$maxsize.'B file';
  69. $flag = true;
  70. }
  71. }
  72. //Read the file
  73. if($flag == flase){
  74. $row = 0;
  75. $handle = fopen($path,'r');
  76. $dataArray = array();
  77. while($data = fgetcsv($handle,$max_column,",")){
  78. $ num = count($data);
  79. if($num < $column){
  80. $msg = 'The file does not meet the specifications and actually contains: '.$num.' column data';
  81. $flag = true;
  82. break;
  83. }
  84. if($flag === flase){
  85. for($i=0;$i<3;$i++){
  86. if($row == 0){
  87. break;
  88. }
  89. //Build data
  90. $dataArray[$row][$i] = $data[$i];
  91. }
  92. }
  93. $row++;
  94. }
  95. }
  96. return $dataArray;
  97. }
  98. }
  99. $param_arr = array(
  100. 'nav' =>array('username','password','email'),
  101. array(0=>array('xiaohai1','123456','xiaohai1@jbxue.com'),
  102. 1=> array('xiaohai2','213456','xiaohai2@jbxue.com'),
  103. 2=>array('xiaohai3','123456','xiaohai3@jbxue.com')
  104. ));
  105. $column = 3;
  106. $csv = new Csv($param_arr, $column);
  107. //$csv->export();
  108. $path = 'C:Documents and SettingsAdministratorTemptxxx.csv';
  109. $import_arr = $csv-> ;import($path,3);
  110. var_dump($import_arr);
  111. ?>
Copy code


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

See all articles