init: Erste Version aus Test-App erstellen
This commit is contained in:
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace TorstenHettstedt\XmlReader\Sax;
|
||||
|
||||
interface XmlReaderInterfaces
|
||||
{
|
||||
|
||||
function tag_open(string $tag_name, array $attributes): void;
|
||||
|
||||
function cdata(string $tag_name, string $cdata): void;
|
||||
|
||||
function tag_close(string $tag_name): void;
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
<?php
|
||||
|
||||
namespace TorstenHettstedt\XmlReader\Sax;
|
||||
|
||||
use InvalidArgumentException;
|
||||
|
||||
class XmlSaxParser
|
||||
{
|
||||
protected $parser;
|
||||
protected XmlReaderInterfaces $xmlReader;
|
||||
protected string $actualTagName = '';
|
||||
|
||||
public function __construct(XmlReaderInterfaces $xml_reader)
|
||||
{
|
||||
$this->xmlReader = $xml_reader;
|
||||
$this->parser = xml_parser_create();
|
||||
|
||||
xml_set_object($this->parser, $this);
|
||||
xml_set_element_handler($this->parser, "tag_open", "tag_close");
|
||||
xml_set_character_data_handler($this->parser, "cdata");
|
||||
}
|
||||
|
||||
public function __destruct()
|
||||
{
|
||||
xml_parser_free($this->parser);
|
||||
unset($this->parser);
|
||||
}
|
||||
|
||||
public function parse($data):void
|
||||
{
|
||||
xml_parse($this->parser, $data);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $path
|
||||
*
|
||||
* @return void
|
||||
* @throws InvalidArgumentException
|
||||
*/
|
||||
public function parseFile(string $path): void
|
||||
{
|
||||
// open xml file
|
||||
if (!($handle = fopen($path, "r"))) {
|
||||
throw new InvalidArgumentException('could not open XML file "' . $path . '".');
|
||||
}
|
||||
|
||||
while ($data = fread($handle, 4096)) { // read xml file
|
||||
$this->parse($data);
|
||||
}
|
||||
}
|
||||
|
||||
/** @noinspection PhpUnusedParameterInspection */
|
||||
protected function tag_open($parser, string $tag_name, array $attributes):void
|
||||
{
|
||||
$this->actualTagName = $tag_name;
|
||||
if ($this->actualTagName !== '') {
|
||||
$this->xmlReader->tag_open($tag_name, $attributes);
|
||||
}
|
||||
}
|
||||
|
||||
/** @noinspection PhpUnusedParameterInspection */
|
||||
protected function cdata($parser, string $cdata):void
|
||||
{
|
||||
if ($this->actualTagName !== '' && trim($cdata) !== '') {
|
||||
$this->xmlReader->cdata($this->actualTagName, $cdata);
|
||||
}
|
||||
}
|
||||
|
||||
/** @noinspection PhpUnusedParameterInspection */
|
||||
protected function tag_close($parser, string $tag_name):void
|
||||
{
|
||||
$this->actualTagName = '';
|
||||
$this->xmlReader->tag_close($tag_name);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user