I have a text file here which I need to be able to convert into rows to extract the second, third, fourth, and fifth values from.
The first 7 values of each row are tab delimited, then there is a newline, then the final three values are tab delimited.
I removed the interrupting newlines so that each row is fully tab delimited.
<?php
$file="140724.txt";
$fopen = fopen($file, "r");
$fread = fread($fopen,filesize("$file"));
fclose($fopen);
$remove = "\n";
split = explode($remove, $fread);
foreach ($split as $string)
{
echo "$string<br><br>";
}
?>
Which produces this.
I'm not sure where to progress from this point. I'm teaching myself PHP and am still quite new to it, so I don't even know if where I've started from is a good place. My instinct is to write the previous output to a new textfile, then create another block of code similar to the first but exploding based on tabs, this time.
Help?
php $myfile = fopen("test. txt", "r") or die("Unable to open file!"); // Output one line until end-of-file while(! feof($myfile)) { $text[] = fgets($myfile); } fclose($myfile); print_r($text); ?>
The str_split() is an inbuilt function in PHP and is used to convert the given string into an array. This function basically splits the given string into smaller strings of length specified by the user and stores them in an array and returns the array.
PHP Read File - fread() The fread() function reads from an open file. The first parameter of fread() contains the name of the file to read from and the second parameter specifies the maximum number of bytes to read.
The is_file() function in PHP is an inbuilt function which is used to check whether the specified file is a regular file or not. The name of the file is sent as a parameter to the is_file() function and it returns True if the file is a regular file else it returns False. Syntax: bool is_file($file)
You can process this file in one go like this:
<?php
$file="140724.txt";
$fopen = fopen($file, 'r');
$fread = fread($fopen,filesize($file));
fclose($fopen);
$remove = "\n";
$split = explode($remove, $fread);
$array[] = null;
$tab = "\t";
foreach ($split as $string)
{
$row = explode($tab, $string);
array_push($array,$row);
}
echo "<pre>";
print_r($array);
echo "</pre>";
?>
The result will be a jagged array:
You will need to clean up the 1st and the last element.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With