Last active
August 17, 2020 09:54
-
-
Save SerginhoLD/65a66b7e33e10873dc4ed2dfb836b1ae to your computer and use it in GitHub Desktop.
XmlReader with node path
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$reader = new SerginhoLD\Xml\XmlReaderWithNodePath(); | |
$reader->open($xmlFilePath); | |
while ($reader->read()) | |
{ | |
if ($reader->nodeType === \XMLReader::ELEMENT && $reader->getNodePath() === '/root/products/product') | |
{ | |
// code | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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