Note that this function does not magically guess the CSV control from a given file, rather it returns what has been priorly set with SplFileObject::setCsvControl().
PHP - Manual: SplFileObject::getCsvControl
2024-12-21
(PHP 5 >= 5.2.0, PHP 7, PHP 8)
SplFileObject::getCsvControl — Get the delimiter, enclosure and escape character for CSV
Gets the delimiter, enclosure and escape character used for parsing CSV fields.
此函数没有参数。
Returns an indexed array containing the delimiter, enclosure and escape character.
版本 | 说明 |
---|---|
7.4.0 | The escape character can now be an empty string. |
7.0.10 | Added the escape character to the returned array. |
示例 #1 SplFileObject::getCsvControl() example
<?php
$file = new SplFileObject("data.txt");
print_r($file->getCsvControl());
?>
以上例程的输出类似于:
Array ( [0] => , [1] => " [2] => \ )
Note that this function does not magically guess the CSV control from a given file, rather it returns what has been priorly set with SplFileObject::setCsvControl().
Seems that this function always returns the same delimiter.
<?php
file_put_contents("A;B;C;D\n0;0;0;0", "test.txt");
$file = new SplFileObject("test.txt");
var_dump($file->getCsvControl());
?>
array(2) {
[0]=>
string(1) ","
[1]=>
string(1) """
}
Given an absolute path to a CSV or any text file and a list of possible delimiters and assuming lines are up to 4096 characters long, I use
<?php
function guess_delimiter($file, $delimiters=[',',';'])
{
$h = fopen($file,'r');
$count = [];
foreach ($delimiters as $del) {
$count[$del] = 0;
while (($bufer = fgets($h, 4096)) !== false) {
$count[$del]+=substr_count($bufer, $del);
}
rewind($h);
}
fclose($h);
return array_search(max($count), $count);
}
官方地址:https://www.php.net/manual/en/splfileobject.getcsvcontrol.php