在PHP中处理XML文件并一点一点地发送数据

时间:2016-10-12 11:43:34

标签: php symfony xmlreader symfony-http-foundation

我正在尝试读取Symfony项目中的XML文件,以将数据发送到前端。

由于XML文件很大,我使用的是XMLReader和SimpleXML的组合(如本主题中所述:How to use XMLReader in PHP?)。

这是我的XML Reader代码:

class XMLReader {

private $xmlFile;
private $reader;

public function __construct($xmlFile = null)
{
    $this->xmlFile = $xmlFile;
}


public function initReader()
{
    $this->reader = new \XMLReader();
    $this->reader->open($this->xmlFile);
}

public function getData()
{
    $products = array();
    $index = 0;
    while ($this->reader->read()) {
        while ($this->reader->name === 'product') {
            $node = new \SimpleXMLElement($this->reader->readOuterXML());
            array_push($products, $node);
            $index++;
            if ($index < 20)
                $this->reader->next();
            else
                break 2;
        }
    }
    return $products;
}

我的目标是一点一点地发送数据,因为它们将显示在带有分页的表格中。这意味着第一次,它将发送20个结果,然后当我们点击第2页时,它将请求接下来的20个结果。

有办法吗?

1 个答案:

答案 0 :(得分:1)

在Symfony中,您可以使用StreamedResponse通过小块发送响应。它通常用于发送大文件,因为它不需要将整个文件加载到内存中,但它也应该满足您的需求。

了解它在doc:http://symfony.com/doc/current/components/http_foundation.html#streaming-a-response

中的用法
相关问题