PHP Conference Japan 2024

SplFileObject::getCsvControl

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

SplFileObject::getCsvControl取得 CSV 的分隔符號、括住符號和跳脫字元

說明

public SplFileObject::getCsvControl(): 陣列

取得用於剖析 CSV 欄位的分隔符號、括住符號和跳脫字元。

參數

此函式沒有參數。

回傳值

返回一個索引陣列,其中包含分隔符號、括住符號和跳脫字元。

更新日誌

版本 說明
7.4.0 跳脫字元現在可以是空字串。
7.0.10 已將跳脫字元新增至回傳的陣列中。

範例

範例 #1 SplFileObject::getCsvControl() 範例

<?php
$file
= new SplFileObject("data.txt");
print_r($file->getCsvControl());
?>

以上範例會輸出類似以下的內容:

Array
(
    [0] => ,
    [1] => "
    [2] => \
)

參見

新增註解

使用者貢獻的註解 3 則註解

greg dot bowler at g105b dot com
9 年前
請注意,此函式並不會神奇地從給定檔案猜測 CSV 控制字元,而是會返回先前使用 SplFileObject::setCsvControl() 設定的內容。
faure dot daniel dot 57 at gmail dot com
3 年前
給定 CSV 或任何文字檔案的絕對路徑以及可能的定界字元列表,並假設每行最多 4096 個字元,我會使用

<?php
函式 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);
}
匿名
11 年前
這個函式似乎總是返回相同的分隔符號。

<?php
file_put_contents
("A;B;C;D\n0;0;0;0", "test.txt");

$file = new SplFileObject("test.txt");
var_dump($file->getCsvControl());
?>

陣列(2) {
[0]=>
字串(1) ","
[1]=>
字串(1) """
}
To Top