text - Reading .txt files with PHP and store information into variables
I have a two.txt
files that I need to read.
The content of the two files is below
log.txt
2013/04/20 01:08:11
and
data.txt
MANUFACTURER: SISYSTEM
MODELNAME: DX1
BIRTHDATE: 19710108
SEX: M
For log.txt i need to store the date from the first line and save it into mySQL database.
For data.txt i need to store information from each line into variables. i.e:
$manufacturer = SISYSTEM;
$modelname = DX1;
$birthdate = 19710108;
$sex = M;
For log.txt i can simply just read the first line using fget and store into one variable. However, for data.text, I am having trouble figuring out how to store multiple variables inside the loop. Here's what I have so far, but I don't know how to assign the values into new variables each time it goes through the while loop. Any help is appreciated!
<?PHP
$file_handle = fopen("data.txt", "r");
while (!feof($file_handle) ) {
$line_of_text = fgets($file_handle);
$parts = explode(':', trim($line_of_text) );
}
fclose($file_handle);
?>
Answer
Solution:
Why do you need them in variables? An associative array ("map") is the cleaner approach
Answer
Solution:
Use variable variables: http://php.net/manual/en/language.variables.variable.php
Use in your while loop:
Answer
Solution:
Note: I don't know how to assign the values into new variables
You can use arrays.
I assume that you've just provided an example of what's in each file - that these patterns may repeat. Before I answer your question, I think it's important you should know that maintaining data in text files is a very bad idea or lots of reasons.
Taking the second file as an example, you've got 2 choices of how you manage this data in PHP - consider your data as a table:
You could either store each row in an array, or each column in an array. And the resulting set of arrays can itself be stored in an array.
How you load and parse the data depends on how consistent the data structure will be (will each entry always be this format, or might it have extra / missing attributes). Whether you read the data into rows or columns depends on how the data is stored in the file and also what you intend doing next with the data.
Answer
Solution:
Inside the
while
loop you can compare the line to see what variable you have to assign: PHP: strcmp - ManualProbably you could use a
switch
statement