0

我正在使用以下内容将页面的剥离内容保存到我服务器上的 csv 文件中。

$strippedpage = str_replace('<br>',' ', $semistrippedpage);
    file_put_contents('yourpage.csv', $strippedpage);

在此之前的代码中,我基本上只是使用 str_replace 删除所有 html 并将其格式化为 csv 文件。

    1-Do you like Science?,
    5,2
    1,6
    3,7
    6,8
    7,9
    85,Love
    6,Ok
    15,Strongly Dislike
    2- Do you enjoy science lessons at school?,
    1,3
    1,4
    5,7
    4,8
    2,9
    78,Love
    21,Ok
    16,Strongly Dislike
    3-How often do you use ICT in Science Lessons? (E.g. microscopes digital cameras easi-speak mics.),
    29,2
    8,3
    11,4
    20,6
    4,7
    27,In Some Lessons
    29,Not At All

字符串中剩下的唯一 html 是用于分隔行的 BR 标记。

如果我将上面的输出从浏览器复制并粘贴到记事本文档中并将其另存为 csv,则它可以正常打开并将每一行显示为单独的行。

我遇到的问题是,如果我在服务器上打开生成的“yourpage.csv”文件,我会得到以下信息:

1-Do you like Science?, 5,2 1,6 3,7 6,8 7,9 85,Love 6,Ok 15,Strongly Dislike 2- Do you enjoy science lessons at school?, 1,3 1,4 5,7 4,8 2,9 78,Love 21,Ok 16,Strongly Dislike 3-How often do you use ICT in Science Lessons? (E.g. microscopes  digital cameras  easi-speak mics.), 29,2 8,3 11,4 20,6 4,7 27,In Some Lessons 29,Not At All 4-How often do you get to do practical Science in lessons?, 1,No Answer 17,2 8,3 14,4 4,6 8,7 5,8 1,9 11,In Every Lesson 56,In Some Lessons 3,

出于某种原因,它只是将它全部放在一行上,我不确定如何将相当于换行符的 csv 添加到代码中,以便每个结果都位于单独的行上,就像我在上面发布的示例一样。

4

3 回答 3

2
$strippedpage = str_replace('<br>',"\n", $semistrippedpage); //for new line
file_put_contents('yourpage.csv', $strippedpage);
于 2013-06-26T14:08:35.520 回答
1

instead of stripping away br's, you might want to replace them with new line tags

I.E> $nl = preg_replace('#<br\s*/?>#i', "\n", $html);

might get you heading in the right direction?

于 2013-06-26T14:10:04.587 回答
1

In PHP, the newline character is usually \n, whereas \r\n is used in most Windows programs (such as Notepad).

Because of that, Windows Notepad doesn't identifies the line breaks.

Try opening your CSV file with another editor (Notepad++ for instance) and see if you get the same result.

Also, I would advise you to use fputcsv to generate your CSV file instead of a simple str_replace, as it is much safer (for example, it can handle special characters).

于 2013-06-26T14:12:41.620 回答