PHP operation CSV File code detailed

Source: Internet
Author: User
Tags foreach

1. Generate Cvs,fputcsv () format the rows as CSV and write to the file pointer

The code is as follows Copy Code

<?php

$list = Array (
' Aaa,bbb,ccc,dddd ',
' 11,22,33 ',
' php ', ' Java '
);
$fp = fopen (' file.csv ', ' W ');
foreach ($list as $line) {
Fputcsv ($fp, Explode (', ', $line));
}
Fclose ($FP);
?>


Small hint, if you have a CSV in Chinese we need to pay attention to Chinese problems, otherwise Chinese garbled will be with you play Oh, the following gives an example to solve Chinese garbled.

The code is as follows Copy Code

<?php
/** by Www.111cn.net * *
$row = 1;
$handle = fopen ("File.csv", "R");
fgetcsv () resolves the read rows and finds the fields in CSV format and returns an array containing the fields.
while ($data = Fgetcsv ($handle, 1000, ",")) {
$num = count ($data);
echo "<p> $num fields in line $row: <br>n";
$row + +;
for ($c =0; $c < $num; $c + +) {
Attention to Chinese garbled problem
$data [$c]=iconv ("GBK", "Utf-8//ignore", $data [$c]);
echo $data [$c]. "<br>n";
}
}
Fclose ($handle);
?>

Read a row of data in a CSV file

The code is as follows Copy Code

<?php
function Get_file_line ($file _name, $line) {
$n = 0;
$handle = fopen ($file _name, ' R ');
if ($handle) {
while (!feof ($handle)) {
+ + $n;
$out = Fgets ($handle, 4096);
if ($line = = $n) break;
}
Fclose ($handle);
}
if ($line = = $n) return $out;
return false;
}
Echo get_file_line ("Windows_2011_s.csv", 10);
?>


Read CSV file number of lines (line range)

  code is as follows copy code
<?php
function Get_file_line ($file _name, $line _star, $line _end) {
$n = 0;
$handle = fopen ($file _name, "R");
if ($hand Le) {
while (!feof ($handle)) {
+ + $n;
$out = Fgets ($handle, 4096);
if ($line _star <= $n) {
$ling [] = $ Out
}
if ($line _end = = $n) break;
}
Fclose ($handle);
}
if ($line _end== $n) return $ling
return false;
}
$aa = Get_file_line ("Windows_2011_s.csv", 11, 20);//From line 11th to 20th
foreach ($aa as $BB) {
echo $bb. <br> ";
}

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.