turn a line into a variable

Hi, I'm trying to open a .txt file ( with content seperated by a hard return ) into a form so changes can be made. Each line has to be converted into a variable to populate the form fields.  ofcourse, After the changes are made, I need to overwrite the old file with a new one with the same name.

So far, I've been able to do a line count but I'm having trouble converting the actual lines into variables.

Can you help?
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Once you've read all of the .txt file's contents into a variable, split it by the carriage return and newline characters:

$arrayoflines = split("\r\n",$contents);

PHONE_NUMBER +014 5 124-564-161
ADDRESS_1 Cnr Etabyte St
ADDRESS_2 Georgia
THIS_THING ''''''234safsdf"
/*** BEGIN Config ***/
// The name
$data_file_name = 'data.txt';

// The character that seperates the variable name from the value - can be anything
$variable_seperator = ' ';

$variables_not_to_save = array(
/*** END Config ***/

/*** BEGIN Write data if submitted ***/
      $file_lock = fopen($data_file_name, 'w+');
      foreach($HTTP_POST_VARS as $variable_name => $variable_value){
            if(!in_array($variable_value, $variables_not_to_save)){
                  fwrite($file_lock, $variable_name.$variable_seperator.$variable_value, strlen($variable_name.$variable_seperator.$variable_value));
/*** END Write data if submitted ***/

/*** BEGIN Read the data from the file ***/
// Read the contents of the data file
$file_contents = file($data_file_name);

// Count how many lines there are
$num_lines = count($file_contents);

// Start to read the lines
for($i = 0; $i < $num_lines; $i++){
      $variable_value = null;

      // For readability we'll define the line we're playing with (also clean up any whitespace after the line)
      $this_line = trim($file_contents[$i]);

      // Seperate the variable name and the value
      $line_bits = explode($variable_seperator, $this_line);

      // Store the variable's name
      $variable_name = current($line_bits);

      // Store the variable's value
            $variable_value .= current($line_bits).$variable_seperator;

      // Now we save the info and define a real PHP variable
      $code = "\$VAR_$variable_name = '".str_replace(array('"', '\''), array('', '\\\''), trim($variable_value))."';\n";
//      echo $code;
      // Clean up so the next line won't grumble about the mess
      unset($this_line, $line_bits, $variable_name, $variable_value, $code);
unset($file_contents, $num_lines);
/*** END Read the data from the file ***/
<title>Some Script</title>
<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
First Name: <input name="FIRST_NAME" value="<?=$VAR_FIRST_NAME?>">
Last Name: <input name="LAST_NAME" value="<?=$VAR_LAST_NAME?>">
Phone Number: <input name="PHONE_NUMBER" value="<?=$VAR_PHONE_NUMBER?>">
Address Line 1: <input name="ADDRESS_1" value="<?=$VAR_ADDRESS_1?>">
Address Line 2: <input name="ADDRESS_2" value="<?=$VAR_ADDRESS_2?>">
Some line of data here: <input name="THIS_THING" value="<?=$VAR_THIS_THING?>">
<input type="submit" value="submit">

I've tested sections the reading section but not the writing section, should be fine.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
what format is your data file in?
Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.


Ascii Man is probably right, but I've been doing PHP for 4 years, and I can't really understand it, so here's my attempt.

First of all we need the format of the file.

Second of all you seem to need to get all of the lines of a file into an array.

PHP provides the file() function to do that for you.


$lines = file("name_of_file.txt") or die("File Read Failed");


$lines is now an array containing every line of the file.

of the following form where the -'s indicate the start and end of the file, and are not part of the file.

Phone Number

You could do something like:


list($firstname, $surname, $address, $phone) = file("file.txt") or die("Error Message");


To put the information back into the file after you've gotten it from the form(assuming you've used Post Method):


file_put_contents("file.txt", join("\n", array($_POST['firstname'], $_POST['surname'], $_POST['address'], $_POST['phone'])) );


If you are using PHP < 4.3 You will have to define the function file_put_contents as follows:

function file_put_contents($filename, $content){
        fwrite(fopen($filename, "w"), $content, strlen($content));
ayendallAuthor Commented:
hey, I just wanted to let ya'll know that I'm going to work on this tonight and see what happens...
ayendallAuthor Commented:
also, if we could step it up a notch... there are multiple text files in the directory. I've been using readdir to get the file list...
ayendallAuthor Commented:
It's a .txt
It's a .txt

That's not really what we meant by format. We realise it is  a text file, but how is the text in the .txt file formated?

Lets say for example you want a file to account for John Smith, who lives in Sydney, whose Phone number is 1234567, and whose email address is john.smith@email.com

You could have the following file(-'s are not part of the file, they simply indicate where the file starts and Ends)

That would be one possible format.

Another possible format would be
John Smith

or, although you did say "content seperated by hard return", you could be refering to different content for different people.

This would be a possible example:
John Smith#Sydney#john.smith@email.com#1234567
Mary Scott#Florida#mary@hotmail.com#7654321
George Bush#Washington#president@whitehouse.gov#1111111

Threre are millions more possible formats, limited only by imagination, that you could be using. We need more info on this. Other wise my(as possibly ASCII_MAN's above solution would do the job.

To finish I'll just post the code for dealing with the third example(with the three people)

$people = file("file.txt");
foreach($people as $person){

I pressed tab(accidently) before I got the chance to finish, here is the code I was writing


$people = file("file.txt");
foreach($people as $person_line){
       list($name, $addr, $email, $phone) = explode("#", $person_line);
       $p[] = array("name" => $name, "addr" => $addr, "email" => $email, "phone" => $phone);

$p is then a two dim array containing every person, and their details.

Eg   $p[0]['name'] == "John Smith"
      $p[1]['addr'] == "Florida"
and $p[2]['phone'] == "1111111"
dont forget to htmlentities your data before putting it into the form

Address Line 1: <input name="ADDRESS_1" value="<?=$VAR_ADDRESS_1?>">

could result in :-
Address Line 1: <input name="ADDRESS_1" value="123 "The" avenue">

hmtlentities would give you
Address Line 1: <input name="ADDRESS_1" value="123 &quot;The&quot; avenue">
but would display on the form as   123 "The" avenue
ayendallAuthor Commented:
Hey everybody, I have finshed going over everything you have shown me.. Thank you so much I have learned alot.

I wound up using a mesh of all your answers but I came up with something close to ASCII_Man's answer. I wish I could award all the points to everyone.

this is something like what I came up with for populating the fields:

$chosen = "$mydir/$file";

$lines = file ($chosen);

foreach ($lines as $line_num => $line)

if ($line_num=="1")
echo "<input type=\"hidden\" value=\"".htmlspecialchars($line)."\" size=30 name=\"lineone\">

if ($line_num=="2")
echo "<input type=\"hidden\" value=\"".htmlspecialchars($line)."\" size=30 name=\"linetwo\">


and this is something like what I came up with for overwriting the data:

Echo "update complete";
$fw = fopen ("$datfile", "w+");

FYI, you can accept multiple answers, and split the points among them however you like.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.