Reputation: 113
I'm using fgets() to pull the first line of a txt file that I made with another program and save it as a string. The problem is that I'd like to assign each word as a different variable.
Here is the first line of my txt file:
1435055708,10.9336,8.2295,11.8359,8.2734,10.8750,8.2148,14.6670,12.9922,
Here is my code:
<?php
$outputFile = fopen("output.txt", "r") or die("Unable to open data log file!");
$firstLine = fgets($outputFile);
echo $firstLine;
?>
This just stores the line as the string $firstLine.
I'm trying to split this line into 9 variables
Timestamp = 1435055708
Channel 0 = 10.9336
Channel 1 = 8.2295
...and so on
Upvotes: 2
Views: 68
Reputation: 79
@MaGnetas solution is correct just an explanation explode will break the firstline by delimiter ',' and return an zero indexed array which you can use as it is or create a list
$arr = explode(',',$firstLine);
Upvotes: 1
Reputation: 5108
If the data structure is always the same in your file you can go like this:
$parts = explode(',', $firstLine);
list($timestamp, $channel0, $channel1, ...) = $parts;
The first line will slice your string into an array (every comma separated value will become a new value in an array).
The second line will take the array values and assign them to your desired variables.
Of course all of this can be joined into a single line:
list($timestamp, $channel0, $channel1, ...) = explode(',', fgets($outputFile));
Upvotes: 6