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 :)
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
)
)
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);
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With