在PHP中解析CSV并尝试在字段内容中保留换行符

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了在PHP中解析CSV并尝试在字段内容中保留换行符脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个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 \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;
}

额外:此函数也可以(如果$header_line)返回一个关联数组,使用第一行作为键名.

脚本宝典总结

以上是脚本宝典为你收集整理的在PHP中解析CSV并尝试在字段内容中保留换行符全部内容,希望文章能够帮你解决在PHP中解析CSV并尝试在字段内容中保留换行符所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。