在PHP中解析CSV并尝试在字段内容中保留换行符 [英] Parsing CSV in PHP and trying to keep line breaks in field contents

查看:88
本文介绍了在PHP中解析CSV并尝试在字段内容中保留换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个csv文件,其中的一列有换行符.该列是一个描述字段,因此它存储文本行,项目符号点,最重要的是换行符-有时在段落之间是两行.为了使事情复杂化,描述字段还包含引号.

I have a csv file in which one of the columns there are line breaks. The column is a description field so it stores lines of text, bulleted points, and most importantly line breaks--and sometimes two between paragraphs. To complicate matters, the description field also contains quotes.

我已经尽我所知将内容(并保持格式设置)转换为变量.我尝试了file_get_contents,str_getcsv和fgetcsv无济于事.其中一个函数使我可以将整个描述字段放入一个变量中,但是却删除了所有新行,因此所有内容都在一个大段中.另一个人分别对描述字段中的每个段落进行了解析,而不是一个单位.

I have tried everything I know to get the content (and keeping the formatting) into a variable. I have tried file_get_contents, str_getcsv and fgetcsv to no avail. One of the functions let me put the entire description field into a variable, but it stripped all the new lines, so everything is in one giant paragraph. Another one separately parsed each paragraph within the description field, instead of one single unit.

这是我的csv文件的常规格式:

This is the general format of my csv file:

"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]=The Great Gatsby和最重要的$array[2]包含描述中的文本以及所有换行符和格式,包括字段本身内的引号.

I'd like to have a variable where $array[0]=391, $array[1]=The Great Gatsby and most importantly $array[2] contains the text in the description with all the line breaks and formatting, including the quotes within the field itself.

或者如果有更好的方法来使用PHP进行解析,请告诉我.

Or if there's a better way to parse this using PHP, please let me know.

推荐答案

如果有人在2019年仍然遇到此问题,我的解决方案是fgetcsv($file).自动遵守文本字段内的换行符.

if someone still having this problem in 2019 my solution was fgetcsv($file). Automatically respect the linebreaks inside text fields.

这篇关于在PHP中解析CSV并尝试在字段内容中保留换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆