Rulli Smith
Rulli Smith

Reputation: 353

Php split text by line and get specific element

I have a big text file, split by new lines and on every line elements split by ';', like this:

1;1;20;3.6;0%;70%;25%;0%;5%;
1;2;80;4;45%;20%;20%;15%;0%;
1;3;80;4;40%;35%;5%;20%;0%;
1;4;20;3.6;15%;40%;38%;5%;2%;
1;5;20;3.6;30%;18%;33%;20%;0%;
1;6;80;4;27%;47%;23%;3%;0%;

What I would like to do is with PHP is to read the file correctly and access a specific element in any row, for example on row 2, element 3 (maybe, [1][2], if considered as indexes) and print it.

<?php
//split by new line
$text = fopen("public/data/data1.txt", "r");

if ($text) {
    while (($lines = fgets($text)) !== false) {
     //split by ;   
        $line = explode(';', $lines);

        //access a specific element 
    }

    fclose($text);
} else {
    // error opening the file.
}
?>

Does somebody know how I could access this elements?

Upvotes: 0

Views: 50

Answers (1)

Andreas
Andreas

Reputation: 23958

You can explode the string twice.
First on lines, then on ;.

$arr = explode(PHP_EOL, $str);
Foreach($arr as &$line){
    $line = explode(";", $line);
}

https://3v4l.org/5fbvZ

Then echo $arr[1][2]; will work as you wanted

Upvotes: 2

Related Questions