0

I want to add a string (the value of a DOM element - $entry = stripslashes($_GET["nameofmytextarea"]);) to the second line of myfile.csv (so as not to delete the header).

I don't care about CSV stuff, everything is already formatted. Just treat it as a text string being added to a text file.

I don't want anything complicated, just skip the first line and "append" above the second line: under the header but above all the other CSV lines.

How hard can that be?

1
  • It's nearly 2012, and you're still running with magic_quotes_gpc? Commented Dec 17, 2011 at 17:19

2 Answers 2

3
$contents = explode("\n", file_get_contents('myfile.csv'), 2);
file_put_contents('myfile.csv', $contents[0]."\n".$entry."\n".$contents[1]);

This should work if the lines are separated by unix-lineendings.
If the file first looks like this:

header
content
content2

and the code is run with $entry = 'test'; it will look like this afterwards:

header
test
content
content2
Sign up to request clarification or add additional context in comments.

3 Comments

Yep, this works, I didn't know you could do that. Thanks for helping a n00b out man!
No Problem :) That's why we are here.
Just be sure to check that $contents[1] is set, or you will end up with a blank line at the end of the file, and an E_NOTICE - that's one reason why I prefer the array_splice() approach...
0

A combination of file() and array_splice() is what you need here:

function prepend_to_csv ($file, $line) {
  if (!$data = file($file)) {
    return FALSE;
  }
  array_splice($data, 1, 0, $line.PHP_EOL);
  return (bool) file_put_contents($file, $data);
}

if (prepend_to_csv('myfile.csv', "this,is,some,data")) {
  echo 'Success';
} else {
  echo 'Fail';
}

Because of the way this method works, you need to ensure that you manually add the EOL to the new line yourself.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.