分解txt文件PHP


Exploding txt file PHP

我在PHP中分解一个txt文件时遇到问题。下面是我想做的一个例子:

Product N°3456788765
price: 0.09
name: carambar

Product N°3456789
price: 9
name: bread

所以基本上,我想要一个数组,比如:

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

在其他问题中,他们使用了爆炸函数。不幸的是,我不知道该对函数说什么,因为这里的分隔符是空行。。。

我试着做一些研究,因为当我在空白行上使用strlen()时,它会显示2个字符。因此,在使用ord()函数后,我发现这两个字符在Ascii模式下分别为13和10,但如果我尝试

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

它就是不起作用。我很想在我的爆炸分隔符中使用这个$string。。。

感谢大家的建议,多年来第一次在这里找到答案:)

试试这样的东西:

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

为您提供:

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

不要让它变得复杂,只需将file()array_chunk()结合使用即可。

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

结果如下:

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

我有两辆chr(13)。chr(10)当产品发生变化时,chr(1)当它只是改变生产线时。所以它现在起作用了!