CSV 파일에 새 줄 추가
만약 내가 서버에 CSV가 저장되어 있다면, 어떻게 PHP를 사용하여 주어진 줄을 쓸 수 있습니까?142,fred,elephants
그것의 바닥까지?
추가할 CSV 파일을 엽니다().fopen
◦문서
$handle = fopen("test.csv", "a");
그런 다음 라인()fputcsv
◦문서을 추가합니다.
fputcsv($handle, $line); # $line is an array of strings (array|string[])
그런 다음 핸들()fclose
◦문서을 닫습니다.
fclose($handle);
파일에 개체 지향 인터페이스 클래스를 사용할 수 있습니다. - SplunkFileObject http://php.net/manual/en/splfileobject.fputcsv.php (PHP 5 > = 5.4.0)
$file = new SplFileObject('file.csv', 'a');
$file->fputcsv(array('aaa', 'bbb', 'ccc', 'dddd'));
$file = null;
이 솔루션은 다음과 같은 이점을 제공됩니다.
<?php
$list = array
(
'Peter,Griffin,Oslo,Norway',
'Glenn,Quagmire,Oslo,Norway',
);
$file = fopen('contacts.csv','a'); // 'a' for append to file - created if doesn't exit
foreach ($list as $line)
{
fputcsv($file,explode(',',$line));
}
fclose($file);
?>
참조: https://www.w3schools.com/php/func_filesystem_fputcsv.asp
각 분할 파일이 원본의 헤더를 유지하기를 원하는 경우, 다음은 hakre의 수정된 버전입니다.
$inputFile = './users.csv'; // the source file to split
$outputFile = 'users_split'; // this will be appended with a number and .csv e.g. users_split1.csv
$splitSize = 10; // how many rows per split file you want
$in = fopen($inputFile, 'r');
$headers = fgets($in); // get the headers of the original file for insert into split files
// No need to touch below this line..
$rowCount = 0;
$fileCount = 1;
while (!feof($in)) {
if (($rowCount % $splitSize) == 0) {
if ($rowCount > 0) {
fclose($out);
}
$out = fopen($outputFile . $fileCount++ . '.csv', 'w');
fputcsv($out, explode(',', $headers));
}
$data = fgetcsv($in);
if ($data)
fputcsv($out, $data);
$rowCount++;
}
fclose($out);
언급URL : https://stackoverflow.com/questions/11399197/add-a-new-line-to-a-csv-file
'programing' 카테고리의 다른 글
os.listdir()를 사용하여 숨겨진 파일을 무시하는 방법은 무엇입니까? (0) | 2023.07.23 |
---|---|
각 TILL의 최대값과 해당 TILL의 항목 수를 사용하여 결과 집합을 만드는 방법 (0) | 2023.07.23 |
없음 값이란 무엇입니까? (0) | 2023.07.23 |
C에서 정적 라이브러리에 링크하는 방법은 무엇입니까? (0) | 2023.07.23 |
PDO ATTR_PERSINT에 대한 완전한 이해 (0) | 2023.07.23 |