PHP txt file explosion

I'm having a problem with txt file extension in PHP. Here's 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

      

For other questions, they used the explosion function. Unfortunately, I don't know what to tell the function, because the delimiters here are empty lines ...

I tried to do some research because when I go with strlen()

on a blank line it shows 2 characters. So after using the function, ord()

I saw that these two characters were 13 and 10 in Ascii mode, but if I try

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

      

It just doesn't work. I'd love to use this one $string

in my rift separator ...

Thank you all for your advice, first post after years of finding answers :)

+3


source to share


3 answers


The result is here:

    $text = file_get_contents('file.txt');
    $temp = explode(chr(13) . chr(10) . chr(13) . chr(10),$text);
    $hands = array();
    foreach($temp as $hand){
        $hand = explode(chr(13) . chr(10),$hand);
        $hand = array_filter($hand);
        array_push($hands,$hand);
        $hand = array_filter($hand);
    }
    dd($hands);

      



I have two chr (13). chr (10) when the product changes and one when it just changes the line. Now it works!

0


source


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

)

      

+4


source


Don't make it hard, just use file()

in conjunction with array_chunk()

.

<?php

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

?>

      

+2


source







All Articles