在PHP中解析CSV并尝试在字段内容中保留换行符
发布时间:2020-12-13 22:53:23 所属栏目:PHP教程 来源:网络整理
导读:我有一个csv文件,其中一个列有换行符.该列是一个描述字段,因此它存储文本行,项目符号点,最重要的是换行符 – 有时两段之间存储.更复杂的是,描述字段也包含引号. 我已经尝试了所有我知道的内容(并保持格式化)为变量.我试过file_get_contents,str_getcsv和fget
我有一个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", 我想要一个变量,其中$array [0] = 391,$array [1] = 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 rn to that function. So first we ensure // that we have Unix line endings only. $csv = str_replace("rn","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; } 额外:此函数也可以(如果$header_line)返回一个关联数组,使用第一行作为键名. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
热点阅读