Search code examples
phpfile-get-contentsexplodeseparator

PHP explode .txt file by new line and separator |


I have a log.txt file with these kind of datas:

2022-08-25 13:16----------817650|xx:xx:xx:xx:xx:xx|user1|10
2022-08-25 13:16----------817856|xx:xx:xx:xx:xx:xx|user1|5

I would like to compare the last values (10 and 5) from the last two lines, but I got stuck in recognizing the lines.

 <?php

    $textCnt  = "./log.txt";
    $contents = file_get_contents($textCnt);
    $arrfields = explode( "|" , $contents);
            
    
    echo $arrfields[3];

    ?>

I got this:

10 2022-08-25 13:16----------817856

instead of

10

Solution

  • This is a job for fgetcsv.

    $fh = fopen('log.txt', 'r');
    
    while(($currRow = fgetcsv($fh, null, '|')))
    {
        echo $currRow[3].PHP_EOL;
    }