php fgetcsv read csv file code

Source: Internet
Author: User
Keywords Network programming PHP tutorial
Tags array code csv data echo file function network

php tutorial fgetcsv read csv file code

function get_csv_contents ($ file_target) {

$ handle = fopen ($ file_target, 'r');

while ($ data = fgetcsv ($ handle, 1000, ",")) {

$ num = count ($ data);
echo "<p> $ num fields in line $ row: <br> n";
$ row ++;
for ($ c = 0; $ c <$ num; $ c ++) {
echo $ data [$ c]. "<br> n" ;;
/ * echo getUTFString ($ data [$ c]) * /
}
}

fclose ($ handle);
}

array fgetcsv (int handle [, int length [, string delimiter [, string enclosure]]])


handle
A valid file pointer generated by fopen (), popen (), or fsockopen ().

length (optional)
Must be greater than the longest line in the CVS file. In PHP 5 this parameter is optional. If you omit (set to 0 in PHP 5.0.4 and later) this parameter, then there is no limit on the length, but this can affect the efficiency of your execution.

delimiter (optional)
Set the field delimiter (only one character allowed), the default is comma.

enclosure (optional)
Set the field surround (only one character allowed), the default is double quotation marks. This parameter is added in PHP 4.3.0.


Similar to fgets (), except that fgetcsv () parses the read line and finds the fields in CSV format and returns an array of those fields.

Fgetcsv () returns FALSE error, including the end of the file encountered.

Note: Blank lines in a CSV file will be returned as an array containing a single null field and will not be treated as an error.

Example 1. Read and display the entire contents of the CSV file

<? php
$ row = 1;
$ handle = fopen ("test.csv", "r");
while ($ data = fgetcsv ($ handle, 1000, ",")) {
$ num = count ($ data);
echo "<p> $ num fields in line $ row: <br> n";
$ row ++;
for ($ c = 0; $ c <$ num; $ c ++) {
echo $ data [$ c]. "<br> n";
}
}
fclose ($ handle);

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.