1

The PHP code I have currently sends the data that is posted in my form to a file called newData.html. I would like it to send the data to a file that is named the same as the product name in the data.

For example, I have a product called the NS-4000. I enter the product's name in the product name blank on my form and submit the form. I want for a file named, NS-4000.html to be created with the other data pieces I have going there. In this case, I would have the name of the project lead, a description of the product and the names of the team members. This is the PHP I have so far:

<?php
    $Name = $_POST['Name'];
    $PLname= $_POST['PLname'];
    $Team_members= $_POST['Team_members'];
    $Description= $_POST['Description'];

    $html = <<<HEREDOC
         Product Name: $Name <br>
         Project Lead: $PLname <br>
         Team Members: $Team_members <br> <br>
         Description: $Description
    HEREDOC;
    file_put_contents('newPage.html', $html);

    header('location: newPage.html');
    exit;

How would I go about having my PHP code create a file with the same name as the product name in the form?

4
  • 3
    Hint: use $Name to construct the filename of the file which will contain your data. Commented Jun 18, 2012 at 20:24
  • Thanks! Dunno why I didn't figure that out... Commented Jun 18, 2012 at 20:36
  • You may want to make use of strtolower for your naming convention, should the name start with a capital letter; e.g. John. Commented Jun 18, 2012 at 20:51
  • Saving with lowercase convention $fp = fopen(strtolower($Name) . ".html", 'w'); or $fp = fopen(strtolower($Name) . 'w'); thought you might need it, just in case. Commented Jun 18, 2012 at 21:17

1 Answer 1

1

You need to use fopen() to create a file. Using "w" as the second parameter allows you to write to create a new file if it doesn't exist. After that you can add contents using fwrite(). I borrowed this code from the fwrite() page and modified for your situation.

<?php
$fp = fopen($Name, 'w');
fwrite($fp, $html);
fclose($fp);

// the content of $Name is now $html
?>
Sign up to request clarification or add additional context in comments.

3 Comments

file_put_contents() that the OP is using in the example is a shortcut method for performing all the steps listed in your answer.
@Brian Glaz - Very cool, I actually hadn't seen that used yet, thanks!
Note that the main reason to use fopen()/fwrite() is to write data in chunk to lower memory usage. Useful when writing big files.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.