-1

PHP developers here ?? I have a PHP function who parse an xml file (using DOMDocument, i'm proficien with this tool). I want to do the same with XMLReader, but i don't understand how XMLReader works...

I want to use XMLReader because it's a light tool.

Feel free to ask me others questions about my issue.

function getDatas($filepath)
{
    $doc = new DOMDocument();
    $xmlfile = file_get_contents($filepath);
    $doc->loadXML($xmlfile);

    $xmlcars = $doc->getElementsByTagName('car');
    $mycars= [];

    foreach ($xmlcars as $xmlcar) {
        $car = new Car();
        $car->setName(
            $xmlcar->getElementsByTagName('id')->item(0)->nodeValue
        );
        $car->setBrand(
            $xmlcar->getElementsByTagName('brand')->item(0)->nodeValue
        );

        array_push($mycars, $car);
    }
    return $mycars;

 }

PS : I'm not a senior PHP dev.

Ahah Thanks.

KitchenLee
  • 105
  • 1
  • 1
  • 6

2 Answers2

0

This is a good example from this topic, I hope it helps you to understand.

$z = new XMLReader;
$z->open('data.xml');

$doc = new DOMDocument;

// move to the first <product /> node
while ($z->read() && $z->name !== 'product');

// now that we're at the right depth, hop to the next <product/> until the end of the tree
while ($z->name === 'product')
{
    // either one should work
    //$node = new SimpleXMLElement($z->readOuterXML());
    $node = simplexml_import_dom($doc->importNode($z->expand(), true));

    // now you can use $node without going insane about parsing
    var_dump($node->element_1);

    // go to next <product />
    $z->next('product');
}
Community
  • 1
  • 1
rvbarreto
  • 683
  • 9
  • 24
0

XMLReader does not, as far as I can tell, have some equivalent way of filtering by an element name. So the closest equivalent to this would be, as mentioned in rvbarreto's answer, to iterate through all elements using XMLReader->read() and grabbing the info you need when the element name matches what you are wanting.'

Alternatively, you might want to check out SimpleXML, which supports filtering using XPath expressions, as well as seeking to a node in the XML using the element structure like they are sub-objects of the main object. For instance, instead of using:

$xmlcar->getElementsByTagName('id')->item(0)->nodeValue;

You would use:

$xmlcar->id[0];

Assuming all of your car elements are at the first level of the XML document tree, the following should work as an example:

function getDatas($filepath) {

    $carsData = new SimpleXMLElement($filepath, NULL, TRUE);

    $mycars = [];

    foreach($carsData->car as $xmlcar) {
        $car = new Car();
        $car->setName($xmlcar->id[0]);
        $car->setBrand($xmlcar->id[0]);
        $mycars[] = $car;
    }

}
Anthony
  • 36,459
  • 25
  • 97
  • 163