Hướng dẫn dùng php fgetcsv trong PHP

Cú pháp

Hàm fgetcsv[] trong PHP có cú pháp như sau:

array fgetcsv [ resource $handle [, int $length [, string $delimiter [, string $enclosure [, string $escape]]]] ];

Định nghĩa và cách sử dụng

Hàm này tương tự hàm fgets[], ngoại trừ việc hàm fgetcsv[] sẽ parse dòng nó đọc sang định dạng CSV và trả về một mảng chứa các trường đã đọc.

Tham số

Tham sốMiêu tả
handle Một con trỏ file hợp lệ trỏ tới file được mở thành công bởi fopen[], popen[], hoặc fsockopen[].
length Phải lớn hơn dòng dài nhất
delimiter Thiết lập trường delimiter [chỉ một ký tự]. Mặc định là một dấu phảy
enclosure Thiết lập trường ký tự enclosure [chỉ một ký tự]. Mặc định là một dấu trích dẫn kép
escape Thiết lập ký tự escape [chỉ một ký tự]. Mặc định là một dấu gạch chéo ngược [\]

Quảng cáo

Trả về giá trị

Trả về một mảng đã được lập chỉ mục chứa các trường đã đọc.

Ví dụ

Ví dụ sau minh họa cách sử dụng của hàm fgetcsv[] trong PHP:

Đã có app VietJack trên điện thoại, giải bài tập SGK, SBT Soạn văn, Văn mẫu, Thi online, Bài giảng....miễn phí. Tải ngay ứng dụng trên Android và iOS.

Theo dõi chúng tôi miễn phí trên mạng xã hội facebook và youtube:

Các bạn ở Hà Nội có thể tham gia khóa học thứ 9 của vietjackteam [đang tuyển sinh] vào cuối tháng 10/2018 do anh Nguyễn Thanh Tuyền, admin vietjack.com trực tiếp giảng dạy tại Hà Nội. Chi tiết nội dung khóa học tham khỏa link : Khóa học Java.Các bạn học CNTT, điện tử viễn thông, đa phương tiện, điện-điện tử, toán tin có thể theo học khóa này. Số lượng các công việc Java hoặc .NET luôn gấp ít nhất 3 lần Android hoặc iOS trên thị trường tuyển dụng. Khóa online= Đi phỏng vấn, Khóa offline= Đi phỏng vấn+ 1.5 tháng thực tập ngoài doanh nghiệp.

Mọi người có thể xem demo nội dung khóa học tại địa chỉ Video demo khóa học Offline

Các bạn ở xa học không có điều kiện thời gian có thể tham dự khóa Java online để chủ động cho việc học tập. Từ tháng 4/2018, VietJack khuyến mại giá SỐC chỉ còn 250k cho khóa học, các bạn có thể trả lại tiền nếu không hài lòng về chất lượng trong 1 tháng, liên hệ facebook admin fb.com/tuyen.vietjack để thanh toán chuyển khoản hoặc thẻ điện thoại, khóa học bằng Tiếng Việt với gần 100 video, các bạn có thể chủ động bất cứ lúc nào, và xem mãi mãi. Thông tin khóa học tại Khóa học Java Online trên Udemy

Follow fanpage của team //www.facebook.com/vietjackteam/ hoặc facebook cá nhân Nguyễn Thanh Tuyền //www.facebook.com/tuyen.vietjack để tiếp tục theo dõi các loạt bài mới nhất về Java,C,C++,Javascript,HTML,Python,Database,Mobile.... mới nhất của chúng tôi.

Các bài học PHP phổ biến khác tại VietJack:

  • PHP - Cú pháp
  • PHP - Các kiểu biến
  • PHP - Hằng [Constant]
  • PHP - Toán tử
  • PHP - Lệnh if, else, switch

tong_hop_ham_trong_php.jsp

Bài viết liên quan

  • 160 bài học ngữ pháp tiếng Anh hay nhất

  • 155 bài học Java tiếng Việt hay nhất

  • 100 bài học Android tiếng Việt hay nhất

  • 247 bài học CSS tiếng Việt hay nhất

  • 197 thẻ HTML cơ bản

  • 297 bài học PHP

  • 101 bài học C++ hay nhất

  • 97 bài tập C++ có giải hay nhất

  • 208 bài học Javascript có giải hay nhất

Cú pháp

Hàm fgetcsv[] trong PHP có cú pháp như sau:

array fgetcsv [ resource $handle [, int $length [, string $delimiter [, string $enclosure [, string $escape]]]] ];

Định nghĩa và cách sử dụng

Hàm này tương tự hàm fgets[], ngoại trừ việc hàm fgetcsv[] sẽ parse dòng nó đọc sang định dạng CSV và trả về một mảng chứa các trường đã đọc.

Tham số

Tham sốMiêu tả
handle Một con trỏ file hợp lệ trỏ tới file được mở thành công bởi fopen[], popen[], hoặc fsockopen[].
length Phải lớn hơn dòng dài nhất
delimiter Thiết lập trường delimiter [chỉ một ký tự]. Mặc định là một dấu phảy
enclosure Thiết lập trường ký tự enclosure [chỉ một ký tự]. Mặc định là một dấu trích dẫn kép
escape Thiết lập ký tự escape [chỉ một ký tự]. Mặc định là một dấu gạch chéo ngược [\]

Quảng cáo

Trả về giá trị

Trả về một mảng đã được lập chỉ mục chứa các trường đã đọc.

Ví dụ

Ví dụ sau minh họa cách sử dụng của hàm fgetcsv[] trong PHP:

Đã có app VietJack trên điện thoại, giải bài tập SGK, SBT Soạn văn, Văn mẫu, Thi online, Bài giảng....miễn phí. Tải ngay ứng dụng trên Android và iOS.

Theo dõi chúng tôi miễn phí trên mạng xã hội facebook và youtube:

Các bạn ở Hà Nội có thể tham gia khóa học thứ 9 của vietjackteam [đang tuyển sinh] vào cuối tháng 10/2018 do anh Nguyễn Thanh Tuyền, admin vietjack.com trực tiếp giảng dạy tại Hà Nội. Chi tiết nội dung khóa học tham khỏa link : Khóa học Java.Các bạn học CNTT, điện tử viễn thông, đa phương tiện, điện-điện tử, toán tin có thể theo học khóa này. Số lượng các công việc Java hoặc .NET luôn gấp ít nhất 3 lần Android hoặc iOS trên thị trường tuyển dụng. Khóa online= Đi phỏng vấn, Khóa offline= Đi phỏng vấn+ 1.5 tháng thực tập ngoài doanh nghiệp.

Mọi người có thể xem demo nội dung khóa học tại địa chỉ Video demo khóa học Offline

Các bạn ở xa học không có điều kiện thời gian có thể tham dự khóa Java online để chủ động cho việc học tập. Từ tháng 4/2018, VietJack khuyến mại giá SỐC chỉ còn 250k cho khóa học, các bạn có thể trả lại tiền nếu không hài lòng về chất lượng trong 1 tháng, liên hệ facebook admin fb.com/tuyen.vietjack để thanh toán chuyển khoản hoặc thẻ điện thoại, khóa học bằng Tiếng Việt với gần 100 video, các bạn có thể chủ động bất cứ lúc nào, và xem mãi mãi. Thông tin khóa học tại Khóa học Java Online trên Udemy

Follow fanpage của team //www.facebook.com/vietjackteam/ hoặc facebook cá nhân Nguyễn Thanh Tuyền //www.facebook.com/tuyen.vietjack để tiếp tục theo dõi các loạt bài mới nhất về Java,C,C++,Javascript,HTML,Python,Database,Mobile.... mới nhất của chúng tôi.

Các bài học PHP phổ biến khác tại VietJack:

  • PHP - Cú pháp
  • PHP - Các kiểu biến
  • PHP - Hằng [Constant]
  • PHP - Toán tử
  • PHP - Lệnh if, else, switch

tong_hop_ham_trong_php.jsp

Bài viết liên quan

  • 160 bài học ngữ pháp tiếng Anh hay nhất

  • 155 bài học Java tiếng Việt hay nhất

  • 100 bài học Android tiếng Việt hay nhất

  • 247 bài học CSS tiếng Việt hay nhất

  • 197 thẻ HTML cơ bản

  • 297 bài học PHP

  • 101 bài học C++ hay nhất

  • 97 bài tập C++ có giải hay nhất

  • 208 bài học Javascript có giải hay nhất

[PHP 4, PHP 5, PHP 7, PHP 8]

fgetcsvGets line from file pointer and parse for CSV fields

Description

fgetcsv[
    resource $stream,
    ?int $length = null,
    string $separator = ",",
    string $enclosure = "\"",
    string $escape = "\\"
]: array|false

Note:

The locale settings are taken into account by this function. If LC_CTYPE is e.g. en_US.UTF-8, files in one-byte encodings may be read wrongly by this function.

Parameters

stream

A valid file pointer to a file successfully opened by fopen[], popen[], or fsockopen[].

length

Must be greater than the longest line [in characters] to be found in the CSV file [allowing for trailing line-end characters]. Otherwise the line is split in chunks of length characters, unless the split would occur inside an enclosure.

Omitting this parameter [or setting it to 0, or null in PHP 8.0.0 or later] the maximum line length is not limited, which is slightly slower.

separator

The optional separator parameter sets the field separator [one single-byte character only].

enclosure

The optional enclosure parameter sets the field enclosure character [one single-byte character only].

escape

The optional escape parameter sets the escape character [at most one single-byte character]. An empty string [""] disables the proprietary escape mechanism.

Note: Usually an enclosure character is escaped inside a field by doubling it; however, the escape character can be used as an alternative. So for the default parameter values "" and \" have the same meaning. Other than allowing to escape the enclosure character the escape character has no special meaning; it isn't even meant to escape itself.

Return Values

Returns an indexed array containing the fields read on success, or false on failure.

Note:

A blank line in a CSV file will be returned as an array comprising a single null field, and will not be treated as an error.

Note: If PHP is not properly recognizing the line endings when reading files either on or created by a Macintosh computer, enabling the auto_detect_line_endings run-time configuration option may help resolve the problem.

Changelog

VersionDescription
8.0.0 length is now nullable.
7.4.0 The escape parameter now also accepts an empty string to disable the proprietary escape mechanism.

Examples

Example #1 Read and print the entire contents of a CSV file

See Also

  • str_getcsv[] - Parse a CSV string into an array
  • explode[] - Split a string by a string
  • file[] - Reads entire file into an array
  • pack[] - Pack data into binary string
  • fputcsv[] - Format line as CSV and write to file pointer

james dot ellis at gmail dot com

13 years ago

If you need to set auto_detect_line_endings to deal with Mac line endings, it may seem obvious but remember it should be set before fopen, not after:

This will work:


This won't, you will still get concatenated fields at the new line position:

shaun at slickdesign dot com dot au

4 years ago

When a BOM character is suppled, `fgetscsv` may appear to wrap the first element in "double quotation marks". The simplest way to ignore it is to progress the file pointer to the 4th byte before using `fgetcsv`.

michael dot arnauts at gmail dot com

10 years ago

fgetcsv seems to handle newlines within fields fine. So in fact it is not reading a line, but keeps reading untill it finds a \n-character that's not quoted as a field.

Example:



Returns:
array[3] {
  [0]=>
  string[5] "col 1"
  [1]=>
  string[4] "col2"
  [2]=>
  string[4] "col3"
}
array[3] {
  [0]=>
  string[29] "this
is
having
multiple
lines"
  [1]=>
  string[8] "this not"
  [2]=>
  string[13] "this also not"
}
array[3] {
  [0]=>
  string[13] "normal record"
  [1]=>
  string[19] "nothing to see here"
  [2]=>
  string[7] "no data"
}

This means that you can expect fgetcsv to handle newlines within fields fine. This was not clear from the documentation.

Sbastien

2 years ago

To use fgetcsv[] with a string instead of a file, you can use the data: wrapper //www.php.net/wrappers.data :

myrddin at myrddin dot myrddin

16 years ago

Here is a OOP based importer similar to the one posted earlier. However, this is slightly more flexible in that you can import huge files without running out of memory, you just have to use a limit on the get[] method

Sample usage for small files:-
-------------------------------------

Sample usage for large files:-
-------------------------------------

And heres the class:-
-------------------------------------

i at camerongreen dot org

4 years ago

This style is shown as an example on this page and in a number of examples on the Internet:



Note, this won't handle new lines within csv fields and thus should probably be avoided.

chris at ocproducts dot com

5 years ago

This function has no special BOM handling. The first cell of the first row will inherit the BOM bytes, i.e. will be 3 bytes longer than expected. As the BOM is invisible you may not notice.

Excel on Windows, or text editors like Notepad, may add the BOM.

Tim Henderson

14 years ago

Only problem with fgetcsv[], at least in PHP 4.x -- any stray slash in the data that happens to come before a double-quote delimiter will break it -- ie, cause the field delimiter to be escaped. I can't find a direct way to deal with it, since fgetcsv[] doesn't give you a chance to manipulate the line before it reads it and parses it...I've had to change all occurrences of '\"' to '" in the file first before feeding ot to fgetcsv[]. Otherwise this is perfect for that Microsoft-CSV formula, deals gracefully with all the issues.

michael dot martinek at gmail dot com

13 years ago

Here's something I put together this morning. It allows you to read rows from your CSV and get values based on the name of the column. This works great when your header columns are not always in the same order; like when you're processing many feeds from different customers. Also makes for cleaner, easier to manage code.

So if your feed looks like this:

product_id,category_name,price,brand_name, sku_isbn_upc,image_url,landing_url,title,description
123,Test Category,12.50,No Brand,0,//www.example.com, //www.example.com/landing.php, Some Title,Some Description

You can do:


If you have any questions or comments regarding this class, they can be directed to as I probably won't be checking back here.



Usage :

jack dot peterson at gmail dot com

11 years ago

If you receive data in the following format:

Time,Dataset1,Dataset2,
timestamp1,item 1 for dataset 1,item1 for dataset2
timestamp2,item 2 for dataset 1,item2 for dataset2

the following code will output a series of arrays grouped by column with the resulting format:
array [
[column 1 title] => array [
[timestamp1] => item1 for dataset1
[timestamp2] => item2 for dataset1
]

[column 2 title] => array [
[timestamp1] => item1 for dataset2
[timestamp2] => item2 for dataset2
]
]

Chủ Đề