prewk/xml-streamer

使用低内存消耗流式处理大型XML文件。

0.5.0 2015-03-09 21:19 UTC

This package is auto-updated.

Last update: 2024-08-29 03:31:25 UTC


README

此项目已停止维护,我建议使用其继任者 xml-string-streamer

关于

作者:oskar.thornblad@gmail.com

贡献者

  • Valiton GmbH
  • Michael Härtl

许可协议:MIT协议

安装

使用composer安装,请将以下内容添加到您的composer.json文件中

{
    "require": {
        "prewk/xml-streamer": "dev-master"
    }
}

然后,运行 composer install(假设您已安装composer。)

用法

扩展类并实现 processNode() 方法。

示例

<?php
class SimpleXmlStreamer extends \Prewk\XmlStreamer
{
    public function processNode($xmlString, $elementName, $nodeIndex)
    {
        $xml = simplexml_load_string($xmlString);
        $something = (string)$xml->Something->SomethingElse->ReadThis;
        echo "$nodeIndex: Extracted string '$something' from parent node '$elementName'\n";     
        return true;
    }
}

$streamer = new SimpleXmlStreamer("myLargeXmlFile.xml");
if ($streamer->parse()) {
    echo "Finished successfully";
} else {
    echo "Couldn't find root node";
}

高级示例

为了提高数据库插入的性能,您还可以使用 chunkCompleted() 方法。该方法在处理完数据块后会被调用。

<?php
class SimpleXmlStreamer extends \Prewk\XmlStreamer
{
    protected $pdo;
    protected $sql = array();
    protected $values = array();

    /**
     * Called after the constructor completed class setup
     */
    public function init()
    {
        $this->pdo = new PDO('mysql:host=localhost;dbname=test', 'user','pass');
    }

    public function processNode($xmlString, $elementName, $nodeIndex)
    {
        $xml = simplexml_load_string($xmlString);
        $this->sql[] = '(?,?,?)';
        $this->values[] = (string)$xml->name;
        $this->values[] = (string)$xml->email;
        $this->values[] = (string)$xml->phone;
    }

    /**
     * Called after a file chunk was processed (16KB by default, see constructor)
     */
    public function chunkCompleted()
    {
        if($this->sql===array()) {
            return;
        }
        $command = $this->pdo->prepare('INSERT INTO mytable VALUES '.implode(',',$this->sql));
        $command->execute($this->values);

        $this->sql = $this->values = array();
    }
}