Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use PHP to convert text file into array

Tags:

php

explode

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?

like image 856
Malignus Avatar asked Jul 23 '14 08:07

Malignus


People also ask

How to convert text file to array in PHP?

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); ?>

Can we convert string to array in PHP?

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.

Which function is used to read an existing file in PHP?

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.

What are PHP files?

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)


1 Answers

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:

enter image description here

You will need to clean up the 1st and the last element.

like image 165
Artur Kędzior Avatar answered Oct 01 '22 19:10

Artur Kędzior