SebastianP
SebastianP

Reputation: 51

Avoid new lines in csv because of carriage return with php

doing my few first steps in PHP and I'm stuck. Been searching SO all afternoon but couldn't come up with a solution. Highly appreciate any advice from experienced devs.

Scenario: Users are asked to fill out a short survey consisting of two textareas. Upon hitting the submit button, the content of the textareas is written to a csv file.

Problem: My problem is that (while it does write the content) whenever people use carriage return in the textarea, it results in a new line in the csv file, thus messing it up. I've spent the afternoon reading up on stackoverflow and trying to use str_replace(); for rewriting all \n with spaces " ", alas to no avail.

Here is my HTML:

<!DOCTYPE html> 
<html>
<head>
<title>Survey name here</title>
<meta charset='utf-8'>
</head>

<body>
<?php
if(!empty($errorMessage)) 
{
echo("<p>Error!</p>\n");
echo("<ul>" . $errorMessage . "</ul>\n");
} 
?>

<div id="content">
<h1>Survey</h1>

<form action="post.php" method="post" id="survey">

<p><strong>Question 1:</strong><br />Do you like it or not?</p>
<p><textarea rows="6" cols="100" name="question1" value="<?=$answer;?>"><?php echo $answer ?></textarea></p>

<p><strong>Question 2:</strong><br />Would you prefer this or that?</p>
<p><textarea rows="6" cols="100" name="question2" value="<?=$answer2;?>"><?php echo $answer2 ?></textarea></p>

<input type="submit" name="formSubmit" value="Submit" id="submit" onclick="return Validate()"/>
</form>
</div><!-- End Content -->

</body>
</html>

And here is the PHP part:

<?php
if($_POST['formSubmit'] == "Submit")
{
$answer1 = $_POST['question1'];
$answer2 = $_POST['question2'];

// report error when not answered
$errorMessage = "";
if(empty($_POST['question1']))
{
$errorMessage .= "<li class='errormsg'>Please answer the question No. 1!</li>";
}
if(empty($_POST['question2']))
{
$errorMessage .= "<li class='errormsg'>Please answer the question No. 2!</li>";
}

// sending to CSV
if(empty($errorMessage)) 
{
str_replace('\r\n', ' ', $answer1 . $answer2);
$fs = fopen("test.csv","a");
fwrite($fs,$answer1 . ";" . $answer2 . "\n");
fclose($fs);

// after submit, head to thank you page 
header("Location: thankyou.php");
exit;
}
}
?>

I figure I'm not applying the str_replace() function correctly. Who can help me?

Upvotes: 1

Views: 955

Answers (2)

Vlad Nikitin
Vlad Nikitin

Reputation: 1951

try

  $string = str_replace(array("\n", "\r"), '', $string);

Upvotes: 1

Matt
Matt

Reputation: 1307

Use fputcsv instead of fwrite.

if(empty($errorMessage)) 
{
    $fs = fopen("test.csv","a");
    fputcsv($fs, Array($answer1, $answer2), ';');
    fclose($fs);

    // after submit, head to thank you page 
    header("Location: thankyou.php");
    exit;
}

As a side note, "\r\n" and '\r\n' are not the same thing in PHP. The first one is "carriage return, new line", the second is litterally "backslash-r, backslash-n"

Upvotes: 1

Related Questions