Solved

turn a line into a variable

Posted on 2003-10-21
12
254 Views
Last Modified: 2008-03-06
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?
0
Comment
Question by:ayendall
  • 4
  • 3
  • 2
  • +3
12 Comments
 
LVL 1

Expert Comment

by:whenpigsfly
ID: 9597556
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);

0
 
LVL 2

Accepted Solution

by:
ASCII_Man earned 250 total points
ID: 9597921
data.txt:
*************************
FIRST_NAME Joe
LAST_NAME Blogs
PHONE_NUMBER +014 5 124-564-161
ADDRESS_1 Cnr Etabyte St
ADDRESS_2 Georgia
THIS_THING ''''''234safsdf"
*************************
form.php:
*************************
<?php
/*** 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(
      'submit'
);
/*** END Config ***/



/*** BEGIN Write data if submitted ***/
if(isset($HTTP_POST_VARS['submit'])){
      $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));
            }
      }
      fclose($file_lock);
}
/*** 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
      while(next($line_bits)){
            $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;
      eval($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 ***/
?>
<html>
<head>
<title>Some Script</title>
</head>
<body>
<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
<hr>
First Name: <input name="FIRST_NAME" value="<?=$VAR_FIRST_NAME?>">
<br>
Last Name: <input name="LAST_NAME" value="<?=$VAR_LAST_NAME?>">
<br>
Phone Number: <input name="PHONE_NUMBER" value="<?=$VAR_PHONE_NUMBER?>">
<br>
Address Line 1: <input name="ADDRESS_1" value="<?=$VAR_ADDRESS_1?>">
<br>
Address Line 2: <input name="ADDRESS_2" value="<?=$VAR_ADDRESS_2?>">
<br>
Some line of data here: <input name="THIS_THING" value="<?=$VAR_THIS_THING?>">
<hr>
<input type="submit" value="submit">
</form>
</body>
</html>
*************************

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

Expert Comment

by:shmert
ID: 9599992
what format is your data file in?
0
 
LVL 6

Expert Comment

by:aolXFT
ID: 9600852
Hi

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.

<?php

$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.

-------
Firstname
Surname
Address
Phone Number
-------

You could do something like:

<?php

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):

<?php

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:

<?php
function file_put_contents($filename, $content){
        fwrite(fopen($filename, "w"), $content, strlen($content));
}
?>
0
 

Author Comment

by:ayendall
ID: 9603451
hey, I just wanted to let ya'll know that I'm going to work on this tonight and see what happens...
0
 

Author Comment

by:ayendall
ID: 9603459
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...
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

Author Comment

by:ayendall
ID: 9603576
It's a .txt
0
 
LVL 6

Expert Comment

by:aolXFT
ID: 9605499
Quote:
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)
--------------
John
Smith
Sydney
1234567
john.smith@email.com
-------------

That would be one possible format.

Another possible format would be
-------------
John Smith
Sydney
john.smith@email.com
1234567
-------------

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)

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


0
 
LVL 6

Expert Comment

by:aolXFT
ID: 9605519
I pressed tab(accidently) before I got the chance to finish, here is the code I was writing

<?php

$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"
0
 
LVL 9

Expert Comment

by:waygood
ID: 9606422
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
0
 

Author Comment

by:ayendall
ID: 9611635
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+");

fwrite($fw,$lineone."\n");
fwrite($fw,$linetwo."\n");
fclose($fw);
0
 
LVL 11

Expert Comment

by:shmert
ID: 9614823
FYI, you can accept multiple answers, and split the points among them however you like.
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Deprecated and Headed for the Dustbin By now, you have probably heard that some PHP features, while convenient, can also cause PHP security problems.  This article discusses one of those, called register_globals.  It is a thing you do not want.  …
These days socially coordinated efforts have turned into a critical requirement for enterprises.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now