Jörg Reinholz: PHP Curl memory Fehler

Beitrag lesen

Moin!

Lesen! Erster Nutzerkommentar bei xml_parse()

Hatte es gerade selbst herausgefunden:

<?php
class Books {
  protected $parser;
  protected $elementStack = array();
  protected $authors = array();

  public function __construct() {
    $this->parser = xml_parser_create();

    xml_set_object($this->parser, $this);

    xml_set_element_handler(
      $this->parser,
      'startElement',
      'endElement'
    );

    xml_set_character_data_handler(
      $this->parser,
      'characterData'
    );

    xml_set_default_handler(
      $this->parser,
      'characterData'
    );
  }

  public function __destruct() {
    xml_parser_free($this->parser);
  }

  /*
  public function readCatalog($catalog) {
    xml_parse(
      $this->parser,
      file_get_contents($catalog),
      TRUE
    );
  }
  */

  public function readCatalog($catalog) {
    $handle = fopen($catalog, "r");
    if ($handle) {
        while ( ($buffer = fgets($handle)) !== false ) {
            xml_parse(
                $this->parser,
                $buffer,
                FALSE
            );
        }
        xml_parse( $this->parser,'',TRUE);
    }
  }


  protected function  startElement($parser, $element, $attributes) {
    array_push($this->elementStack, $element);

    if ($element == 'BOOK') {
      $this->authors = array();
    }
  }

  protected function endElement($parser, $element) {
    array_pop($this->elementStack);
  }

  protected function characterData($parser, $cdata) {
    $level   = sizeof($this->elementStack) - 1;
    $element = $this->elementStack[$level];

    switch($element) {
        case 'AUTHOR': {
          $this->authors[] = $cdata;
        }
        break;

        case 'TITLE': {
          print 'Autoren: ' . implode(', ', $this->authors) . "\n";
          print 'Titel: ' . $cdata . "\n";
        }
        break;

        case 'ISBN': {
          print 'ISBN: ' . $cdata . "\n\n";
        }
        break;
    }
  }
}

$books = new Books;
$books->readCatalog('books.xml');
?>

books.xml:

<BOOKS>
    <BOOK>
        <AUTHOR>Sebastian Bergmann</AUTHOR>
        <TITLE>Professionelle Softwareentwicklung mit PHP 5</TITLE>
        <ISBN>ISBN: 3-89864-229-1</ISBN>
    </BOOK>
    <BOOK>
        <AUTHOR>Hakan Kücükyilmaz, Thomas M. Haas, Alexander Merz</AUTHOR>
        <TITLE>PHP 5</TITLE>
        <ISBN>3-89864-236-4</ISBN>
    </BOOK>
</BOOKS>

Jörg Reinholz