【问题标题】:Exploding txt file PHP爆炸txt文件PHP
【发布时间】:2016-08-29 06:31:41
【问题描述】:

我在用 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...

谢谢大家的建议,多年寻找答案后第一次在这里发帖:)

【问题讨论】:

标签: php arrays file


【解决方案1】:

试试这样的:

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

)

【讨论】:

  • 它并不总是 "\n" 可能希望提供一种覆盖所有选项的方法 (PHP_EOL)
  • 第一个解决方案不起作用,explode() 函数期望接收一个字符串参数和第二个。 $file 是一个字符串数组。每行都是数组的一行...第二种解决方案行不通,因为我的行数并不总是相同...
  • 是的,抱歉,取决于 PHP 版本。我的版本没有这个错误。您必须先单独爆炸才能不会出现该错误。
  • 所以你并不总是有三组那么你的意思是什么?
  • 我得到完全相同的错误:explode() expects parameter 2 to be string, array given 在线 $value = explode("\n",$file);。我不明白为什么把它拿出来函数参数会改变什么?
【解决方案2】:

不要太复杂,只需将file()array_chunk()结合使用即可。

<?php

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

?>

【讨论】:

  • 我并不经常需要逐行读取文件的能力,但我不知道 FILE_SKIP_EMPTY_LINES 是该功能中的一个选项...很高兴知道。
  • @Rasclatt 是的,如果你想忽略每行末尾的换行符,还有另一个标志。 (我个人经常使用file()
  • 好吧,无论如何,你得到了三个答案中最好的答案!干杯。
  • 我认为您的解决方案的问题是因为产品功能的行数可能会有所不同..
  • @El_Matella 如果是这种情况,您可以删除过滤器,然后检查第一个空行何时出现,然后将数组分块并删除空行
【解决方案3】:

结果在这里:

    $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) 当产品改变时,一个当它只是改变生产线时。所以它现在可以工作了!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-06
    • 2013-02-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多