Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exploding txt file PHP

Tags:

arrays

file

php

I am having a problem exploding a txt file in PHP. Here is an example of what I want to do:

Product N°3456788765
price: 0.09
name: carambar


Product N°3456789
price: 9
name: bread

So basically, I would like to have an array like:

array
    [0] => 
           [0] => Product N°3456788765
           [1] => price: 0.09
           [2] => name: carambar
    [] => 
           [0] => Product N°3456789
           [1] => price: 9
           [2] => name: bread

In the others questions, they used the explode function. Unfortunately, I don't know what to say to the function because delimiters are blank lines here...

I tried to make some research because when I go with a strlen() on a blank line, it shows 2 caracters. So after using ord() function, I saw that these two caracters were 13 and 10 in Ascii mode, but if I try a

$string = chr(13) . chr(10);
strcmp($string,$blankline); 

It just doesn't work. I would have loved to use this $string in my explode delimiter...

Thank you all for you advices, first post here after many years finding answers :)

like image 289
Hammerbot Avatar asked Sep 17 '26 15:09

Hammerbot


2 Answers

Try something like this:

$file   =   file_get_contents("text.txt");
// This explodes on new line
// As suggested by @Dagon, use of the constant PHP_EOL
// is a better option than \n for it's universality
$value  =   explode(PHP_EOL,$file);
// filter empty values
$array  =   array_filter($value);
// This splits the array into chunks of 3 key/value pairs
$array  =   array_chunk($array,3);

Gives you:

Array
(
    [0] => Array
        (
            [0] => Product N°3456788765
            [1] => price: 0.09
            [2] => name: carambar
        )

    [1] => Array
        (
            [0] => Product N°3456789
            [1] => price: 9
            [2] => name: bread
        )

)
like image 63
Rasclatt Avatar answered Sep 20 '26 04:09

Rasclatt


Don't make it complicated, just use file() combined with array_chunk().

<?php

    $lines = file("yourTextFile.txt", FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES);
    $chunked = array_chunk($lines, 3);
    print_r($chunked);

?>
like image 45
Rizier123 Avatar answered Sep 20 '26 05:09

Rizier123



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!