Skip to content
Advertisement

Add a column header row if not exist in PHP

I have an html form on my web site. When the form is filled out and the submit button is clicked the data is stored on my server in a csv text file. I want to add a column header row if it doesn’t exist. My code adds the header each time new data is entered whether it exists or not, even though I have an if statement that says add if the header row does not exist. What do I need to change so that the column header row only gets added if it doesn’t exist?

JavaScript

Advertisement

Answer

After much struggling I got it right. First check if the file exists before opening, if not add the header. Here is the code that works as expected.

JavaScript

Note, the end of the $header string, r, not rn, also the end of the $savestring, r not rn. With the n removed the line spacing is single. With the rn the line spacing is double.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement