xmlParser.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. <?php
  2. namespace XmlStroller;
  3. class XmlNode implements \Iterator
  4. {
  5. private $itPosition;
  6. private $xml_name;
  7. private $xml_value;
  8. private $xml_parent;
  9. private $xml_children;
  10. private $xml_attributes;
  11. private function __construct($parent, $name =null)
  12. {
  13. $this->xml_children = array();
  14. $this->xml_name = $name;
  15. $this->xml_value = null;
  16. $this->xml_parent = $parent;
  17. $this->xml_attributes = array();
  18. $this->itPosition = 0;
  19. }
  20. private function doParse(&$reader)
  21. {
  22. while ($reader->read())
  23. {
  24. if ($reader->nodeType == \XMLReader::ELEMENT)
  25. {
  26. $i = new self($this, $reader->name);
  27. if ($reader->moveToFirstAttribute())
  28. {
  29. $i->xml_attributes[$reader->name] = $reader->value;
  30. while ($reader->moveToNextAttribute())
  31. $i->xml_attributes[$reader->name] = $reader->value;
  32. }
  33. $i->doParse($reader);
  34. $this->xml_children[] = $i;
  35. }
  36. else if ($reader->nodeType == \XMLReader::END_ELEMENT)
  37. return;
  38. else if ($reader->nodeType == \XMLReader::TEXT)
  39. $this->xml_value = $reader->value;
  40. else if ($reader->nodeType == \XMLReader::WHITESPACE || $reader->nodeType == \XMLReader::SIGNIFICANT_WHITESPACE)
  41. ;
  42. }
  43. }
  44. public static function parse($data)
  45. {
  46. $root = new self(null, null);
  47. $reader = new \XMLReader();
  48. $reader->XML($data);
  49. $root->doParse($reader);
  50. return $root;
  51. }
  52. public function current()
  53. {
  54. return $this->xml_children[$this->itPosition];
  55. }
  56. public function key()
  57. {
  58. return $this->itPosition;
  59. }
  60. public function next()
  61. {
  62. $this->itPosition++;
  63. }
  64. public function rewind()
  65. {
  66. $this->itPosition = 0;
  67. }
  68. public function valid()
  69. {
  70. return isset($this->xml_children[$this->itPosition]);
  71. }
  72. public function getName()
  73. { return $this->xml_name; }
  74. public function attributes()
  75. { return array_merge($this->xml_attributes); }
  76. public function __clone()
  77. {
  78. $r = new self(null, $this->xml_name);
  79. $r->xml_value = $this->xml_value;
  80. $r->xml_attributes = array_merge($this->xml_attributes);
  81. $r->xml_children = array();
  82. foreach ($this->xml_children as $j)
  83. {
  84. $_j = clone($j);
  85. $_j->xml_parent = $r;
  86. $r->xml_children[] = $_j;
  87. }
  88. return $r;
  89. }
  90. public function __toString()
  91. { return $this->xml_value == null ? $this->xml_name : $this->xml_value; }
  92. public function parent()
  93. { return $this->xml_parent; }
  94. }