[扩展推荐] PHP 7 stream-parser 支持多格式的文件流解析器(超大文件 xml/JSON/CSV 读取解析的方案)

file

PHP 7 Stream Parser 是由 Sergio Ródenas 开发的扩展包,用于为 PHP 提供多格式文件流解析。使用 pull 解析器的流在大型文档中比 DOM 加载更加有效。

下面的示例展示了结合 Laravel 队列使用流式解析器:

StreamParser::xml("https://example.com/users.xml")->each(function(Collection $user){
    dispatch(new App\Jobs\SendEmail($user));
});

以下方的 XML 数据为例,流式解析器与「集合」协作得很好,结果非常清晰:

<bookstore>
    <book ISBN="10-000000-001">
        <title>The Iliad and The Odyssey</title>
        <price>12.95</price>
        <comments>
            <userComment rating="4">
                Best translation I've read.
            </userComment>
            <userComment rating="2">
                I like other versions better.
            </userComment>
        </comments>
    </book>
    [...]
</bookstore>

PHP的代码以及输出的例子:

StreamParser::xml("https://example.com/books.xml")->each(function(Collection $book){
    var_dump($book);
    var_dump($book->get('comments')->toArray());
});

// 输出
class Illuminate\Support\Collection#19 (1) {
  protected $items =>
  array(4) {
    'ISBN' =>
    string(13) "10-000000-001"
    'title' =>
    string(25) "The Iliad and The Odyssey"
    'price' =>
    string(5) "12.95"
    'comments' =>
    class Illuminate\Support\Collection#17 (1) {
      protected $items =>
      array(2) {
        ...
      }
    }
  }
}
array(2) {
  [0] =>
  array(2) {
    'rating' =>
    string(1) "4"
    'userComment' =>
    string(27) "Best translation I've read."
  }
  [1] =>
  array(2) {
    'rating' =>
    string(1) "2"
    'userComment' =>
    string(29) "I like other versions better."
  }
}

下面是使用 CSV 的使用示例:

title,price,comments
The Iliad and The Odyssey,12.95,"Best translation I've read.,I like other versions better."
Anthology of World Literature,24.95,"Needs more modern literature.,Excellent overview of world literature."

接下来是使用文件流解析器的代码和输出:

StreamParser::csv("https://example.com/books.csv")->each(function(Collection $book){
    var_dump($book->get('comments')->last());
});

// 输出
string(29) "I like other versions better."
string(39) "Excellent overview of world literature."

了解更多

你可以在 GitHub 上了解关于此安装包的更多信息,并且可以使用 composer require Rodenastyle/stream-parser 来进行安装使用。README 还提到了这篇文章,这里有关于 processing XML files via DOM vs. Streaming 的说明。

本文中的所有译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。

原文地址:https://laravel-news.com/php-7-multi-for...

译文地址:https://learnku.com/laravel/t/15006/exte...

本帖已被设为精华帖!
本文为协同翻译文章,如您发现瑕疵请点击「改进」按钮提交优化建议
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
讨论数量: 2
Summer

曾经处理过 1 G 多的一个 JSON 文件,不使用 stream-parser 的方案,基本上就是没法。

5年前 评论

苦于在找这个解决方案,我先试试

4年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!