Skip to content

Instantly share code, notes, and snippets.

@SerginhoLD
Last active August 17, 2020 09:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save SerginhoLD/65a66b7e33e10873dc4ed2dfb836b1ae to your computer and use it in GitHub Desktop.
Save SerginhoLD/65a66b7e33e10873dc4ed2dfb836b1ae to your computer and use it in GitHub Desktop.
XmlReader with node path
<?php
$reader = new SerginhoLD\Xml\XmlReaderWithNodePath();
$reader->open($xmlFilePath);
while ($reader->read())
{
if ($reader->nodeType === \XMLReader::ELEMENT && $reader->getNodePath() === '/root/products/product')
{
// code
}
}
<?php
namespace SerginhoLD\Xml;
class XmlReaderWithNodePath extends \XMLReader
{
private $nodePath = [];
/**
* @return bool
*/
public function read()
{
$read = parent::read();
if ($read && ($this->nodeType === self::ELEMENT || $this->nodeType === self::END_ELEMENT))
{
$this->nodePath[$this->depth] = $this->localName;
$this->nodePath = array_slice($this->nodePath, 0, $this->depth + 1);
}
return $read;
}
/**
* @return string|null "/root/products/product"
*/
public function getNodePath()
{
return !empty($this->nodePath) ? '/' . implode('/', $this->nodePath) : null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment