0

I am trying to read an XML file in a Symfony project, to send the data to the front end.

As the XML file is huge, I am using a combination of XMLReader and SimpleXML (as suggested in this thread: How to use XMLReader in PHP?).

Here is my code for the 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;
}

My aim is to send the data little by little, as they will be displayed in a table with pagination. Which means the first time, it will send 20 results, and then when we click page 2, it will request the next 20 results.

Is there a way to do that?

Community
  • 1
  • 1
Mahcih
  • 23
  • 5
  • 4
    Not really a good idea as such, since that basically means that you have to parse the xml file _each time_ a new page in the table is requested. Instead you could process the whole file and transfer it, then use client side logic for the pagination (javascript). That is easier and much more appealing, but will only work up to a reasonable amount of data. If that is not an option then you should parse the xml file into a database and deliver the paginated data from there. – arkascha Oct 12 '16 at 11:49
  • arkascha has an point there you could parse XML in javascript and use xpath queries to select the nodes you need to get the pages – Raymond Nijland Oct 12 '16 at 12:22

1 Answers1

1

In Symfony you can send response by small chunks using StreamedResponse. It's usually used to send large files because it doesn't require loading the entire file to memory but it should serve your needs as well.

See how it's used in the doc: http://symfony.com/doc/current/components/http_foundation.html#streaming-a-response

martin
  • 93,354
  • 25
  • 191
  • 226