我有一个 csv 文件,其中一列有换行符。该列是一个描述字段,因此它存储文本行、项目符号点和最重要的换行符 - 有时段落之间有两个。更复杂的是,描述字段还包含引号。
我已经尝试了我所知道的一切来将内容(并保持格式)放入一个变量中。我试过 file_get_contents、str_getcsv 和 fgetcsv 都无济于事。其中一个函数让我将整个描述字段放入一个变量中,但它删除了所有新行,因此所有内容都在一个巨大的段落中。另一个单独解析描述字段中的每个段落,而不是单个单元。
这是我的 csv 文件的一般格式:
"391","The Great Gatsby","The Great Gatsby, F. Scott Fitzgerald’s third book, stands as the supreme achievement of his career.
This exemplary novel of the Jazz Age has been acclaimed by generations of readers. The story of the fabulously wealthy Jay Gatsby and his love for the beautiful Daisy Buchanan, of lavish parties on Long Island at a time when The New York Times noted “gin was the national drink and sex the national obsession,” it is an exquisitely crafted tale of America in the 1920s.
The Great Gatsby is one of the great classics of twentieth-century literature.","No","Yes",
Run Code Online (Sandbox Code Playgroud)
我想要一个变量 where $array[0]=391,$array[1]=The Great Gatsby最重要的是$array[2]包含描述中的文本以及所有换行符和格式,包括字段本身内的引号。
或者如果有更好的方法来使用 PHP 解析它,请告诉我。
我最近自己为这个用例编写了一个函数。
PHP 函数str_getcsv()用于解释单行CSV数据。通常,您可以简单地将文件分解为新行,然后单独解析每一行,但是当字段本身可能包含新行时该怎么办?
技巧是使用str_getcsv() 两次:一次将文件分割成行,再次分割每个单独的行。
/**
* Receives CSV string and returns as an array.
*
* *************************************************************************
*
* Based on code by fab at tradermail dot info at http://php.net/manual/en/function.str-getcsv.php#119666
*/
function csv_to_array($csv, $delimiter=',', $header_line=true) {
// CSV from external sources may have Unix or DOS line endings. str_getcsv()
// requires that the "delimiter" be one character only, so we don't want
// to pass the DOS line ending \r\n to that function. So first we ensure
// that we have Unix line endings only.
$csv = str_replace("\r\n", "\n", $csv);
// Read the CSV lines into a numerically indexed array. Use str_getcsv(),
// rather than splitting on all linebreaks, as fields may themselves contain
// linebreaks.
$all_lines = str_getcsv($csv, "\n");
if (!$all_lines) {
return false;
}
$csv = array_map(
function(&$line) use ($delimiter) {
return str_getcsv($line, $delimiter);
},
$all_lines
);
if ($header_line) {
// Use the first row's values as keys for all other rows.
array_walk(
$csv,
function(&$a) use ($csv) {
$a = array_combine($csv[0], $a);
}
);
// Remove column header row.
array_shift($csv);
}
return $csv;
}
Run Code Online (Sandbox Code Playgroud)
额外奖励:该函数还可以(如果$header_line)返回一个关联数组,使用第一行作为键名。
| 归档时间: |
|
| 查看次数: |
5048 次 |
| 最近记录: |