示例#1
3
 public function start_process()
 {
     if (!$this->path_to_xml_file) {
         return false;
     }
     if (!$this->valid_xml) {
         return false;
     }
     $this->archive_builder = new \eol_schema\ContentArchiveBuilder(array('directory_path' => DOC_ROOT . 'temp/xml_to_archive/'));
     $this->taxon_ids = array();
     $this->media_ids = array();
     $this->vernacular_name_ids = array();
     $this->reference_ids = array();
     $this->agent_ids = array();
     $reader = new \XMLReader();
     $file = file_get_contents($this->path_to_xml_file);
     $file = iconv("UTF-8", "UTF-8//IGNORE", $file);
     $reader->XML($file);
     $i = 0;
     while (@$reader->read()) {
         if ($reader->nodeType == \XMLReader::ELEMENT && $reader->name == "taxon") {
             $taxon_xml = $reader->readOuterXML();
             $t = simplexml_load_string($taxon_xml, null, LIBXML_NOCDATA);
             if ($t) {
                 $this->add_taxon_to_archive($t);
             }
             $i++;
             if ($i % 100 == 0) {
                 echo "Parsed taxon {$i} : " . time_elapsed() . "\n";
             }
             // if($i >= 5000) break;
         }
     }
     $this->archive_builder->finalize();
 }
 private function writeReaderImpl(XMLWriter $writer, XMLReader $reader)
 {
     switch ($reader->nodeType) {
         case XMLReader::ELEMENT:
             $writer->startElement($reader->name);
             if ($reader->moveToFirstAttribute()) {
                 do {
                     $writer->writeAttribute($reader->name, $reader->value);
                 } while ($reader->moveToNextAttribute());
                 $reader->moveToElement();
             }
             if ($reader->isEmptyElement) {
                 $writer->endElement();
             }
             break;
         case XMLReader::END_ELEMENT:
             $writer->endElement();
             break;
         case XMLReader::COMMENT:
             $writer->writeComment($reader->value);
             break;
         case XMLReader::SIGNIFICANT_WHITESPACE:
         case XMLReader::TEXT:
             $writer->text($reader->value);
             break;
         case XMLReader::PI:
             $writer->writePi($reader->name, $reader->value);
             break;
         default:
             XMLReaderNode::dump($reader);
     }
 }
示例#3
0
文件: XHTML.php 项目: philip/phd
 public static function generateAcronymInfo($filename)
 {
     static $info;
     if ($info) {
         return $info;
     }
     $r = new \XMLReader();
     if (!$r->open($filename)) {
         throw new \Exception("Could not open file for accessing acronym information:  {$filename}");
     }
     $acronyms = array();
     while ($r->read()) {
         if ($r->nodeType != \XMLReader::ELEMENT) {
             continue;
         }
         if ($r->name == "term") {
             $r->read();
             $k = $r->value;
             $acronyms[$k] = "";
         } else {
             if ($r->name == "simpara") {
                 $r->read();
                 $acronyms[$k] = $r->value;
             }
         }
     }
     $info = $acronyms;
     return $acronyms;
 }
 /**
  * @param FeedTypeInterface $type
  * @param OutputInterface   $output
  *
  * @return int
  */
 protected function validate(FeedTypeInterface $type, OutputInterface $output)
 {
     $file = $this->exporter->getFeedFilename($type);
     if (!file_exists($file)) {
         throw new FileNotFoundException(sprintf('<error>Feed "%s" has not yet been exported</error>', $type->getName()));
     }
     $options = LIBXML_NOENT | LIBXML_COMPACT | LIBXML_PARSEHUGE | LIBXML_NOERROR | LIBXML_NOWARNING;
     $this->reader = new \XMLReader($options);
     $this->reader->open($file);
     $this->reader->setParserProperty(\XMLReader::SUBST_ENTITIES, true);
     //        foreach ($type->getNamespaces() as $name => $location) {
     //            $this->reader->setSchema($location);
     //        }
     libxml_clear_errors();
     libxml_use_internal_errors(true);
     libxml_disable_entity_loader(true);
     $progress = new ProgressBar($output);
     $progress->start();
     // go through the whole thing
     while ($this->reader->read()) {
         if ($this->reader->nodeType === \XMLReader::ELEMENT && $this->reader->name === $type->getItemNode()) {
             $progress->advance();
             $this->currentItem = $this->reader->readOuterXml();
         }
         if ($error = libxml_get_last_error()) {
             throw new \RuntimeException(sprintf('[%s %s] %s (in %s - line %d, column %d)', LIBXML_ERR_WARNING === $error->level ? 'WARNING' : 'ERROR', $error->code, trim($error->message), $error->file ? $error->file : 'n/a', $error->line, $error->column));
         }
     }
     $progress->finish();
 }
示例#5
0
文件: clio.php 项目: cul/findingaids
function getClioNum($appurl, $link)
{
    $clio = $current = $currentA = "";
    $reader = new XMLReader();
    $clioQ = $appurl . '/getSingleStuff.xq?doc=' . $link . '_ead.xml&section=summary';
    $reader->open($clioQ);
    while ($reader->read()) {
        if ($reader->name == "unitid" && $reader->getAttribute("type") == "clio") {
            if ($reader->nodeType == XMLReader::ELEMENT) {
                $currentA = "clio";
            } else {
                if ($reader->nodeType == XMLReader::END_ELEMENT) {
                    $currentA = "";
                }
            }
        }
        //echo "{$reader->name} and $currentA<br />";
        if ($reader->name == "#text" && $currentA == "clio") {
            $clio = $reader->value;
            // there can be only one
        }
    }
    // end WHILE
    $reader->close();
    return $clio;
}
示例#6
0
 /**
  * Parses a specific XML file
  *
  * @param string $inputFile File to parse
  * @return \Generator
  */
 public function parse($inputFile)
 {
     $DCNamespace = 'http://purl.org/rss/1.0/modules/content/';
     $WPNamespace = 'http://wordpress.org/export/1.2/';
     $reader = new \XMLReader();
     $dom = new \DOMDocument('1.0', 'UTF-8');
     $reader->open($inputFile);
     while ($reader->read() && $reader->name !== 'item') {
     }
     while ($reader->name == 'item') {
         $xml = simplexml_import_dom($dom->importNode($reader->expand(), true));
         $wpItems = $xml->children($WPNamespace);
         $content = $xml->children($DCNamespace)->encoded;
         $categories = [];
         $tags = [];
         foreach ($xml->category as $category) {
             if ('category' == $category->attributes()->domain) {
                 $categories[] = (string) $category;
             }
             if ('post_tag' == $category->attributes()->domain) {
                 $tags[] = (string) $category;
             }
         }
         if ($wpItems) {
             $post_type = (string) $wpItems->post_type;
             $data = ['type' => $post_type, 'post_date' => new \DateTime((string) $wpItems->post_date), 'title' => (string) $xml->title, 'content' => (string) $content, 'tags' => $tags, 'categories' => $categories];
             (yield $data);
         }
         $reader->next('item');
     }
 }
示例#7
0
 /**
  * @throws RuntimeException
  * @return array of arrays.
  *         array( 'dumpKey' => array( 'match1', 'match2' ) )
  */
 public function scan()
 {
     $openSuccess = $this->reader->open($this->dumpLocation);
     if (!$openSuccess) {
         throw new RuntimeException('Failed to open XML: ' . $this->dumpLocation);
     }
     $result = array();
     foreach ($this->query as $queryKey => $query) {
         $result[$queryKey] = array();
         // Make sure keys are returned even if empty
     }
     while ($this->reader->read() && $this->reader->name !== 'page') {
     }
     while ($this->reader->name === 'page') {
         $element = new SimpleXMLElement($this->reader->readOuterXML());
         $page = $this->getPageFromElement($element);
         foreach ($this->query as $queryKey => $query) {
             $match = $this->matchPage($page, $query);
             if ($match) {
                 //TODO allow the user to choose what to return
                 $result[$queryKey][] = $page->getTitle()->getTitle();
             }
         }
         $this->reader->next('page');
     }
     $this->reader->close();
     return $result;
 }
 public function parseErrorResponse($statusCode, $content, MnsException $exception = NULL)
 {
     $this->succeed = FALSE;
     $xmlReader = new \XMLReader();
     try {
         $xmlReader->XML($content);
         $result = XMLParser::parseNormalError($xmlReader);
         if ($result['Code'] == Constants::TOPIC_NOT_EXIST) {
             throw new TopicNotExistException($statusCode, $result['Message'], $exception, $result['Code'], $result['RequestId'], $result['HostId']);
         }
         if ($result['Code'] == Constants::INVALID_ARGUMENT) {
             throw new InvalidArgumentException($statusCode, $result['Message'], $exception, $result['Code'], $result['RequestId'], $result['HostId']);
         }
         if ($result['Code'] == Constants::MALFORMED_XML) {
             throw new MalformedXMLException($statusCode, $result['Message'], $exception, $result['Code'], $result['RequestId'], $result['HostId']);
         }
         throw new MnsException($statusCode, $result['Message'], $exception, $result['Code'], $result['RequestId'], $result['HostId']);
     } catch (\Exception $e) {
         if ($exception != NULL) {
             throw $exception;
         } elseif ($e instanceof MnsException) {
             throw $e;
         } else {
             throw new MnsException($statusCode, $e->getMessage());
         }
     } catch (\Throwable $t) {
         throw new MnsException($statusCode, $t->getMessage());
     }
 }
示例#9
0
 protected function readNext(XMLReader $reader)
 {
     do {
         if ($this->isStartElement('ancode')) {
             $pos_id = (int) $reader->getAttribute('pos_id');
             if (!isset($this->poses[$pos_id])) {
                 throw new Exception("Invalid pos id '{$pos_id}' found in ancode '" . $reader->getAttribute('id') . "'");
             }
             $pos = $this->poses[$pos_id];
             $ancode = new phpMorphy_Dict_Ancode($reader->getAttribute('id'), $pos['name'], $pos['is_predict']);
             while ($this->read()) {
                 if ($this->isStartElement('grammem')) {
                     $grammem_id = (int) $reader->getAttribute('id');
                     if (!isset($this->grammems[$grammem_id])) {
                         throw new Exception("Invalid grammem id '{$grammem_id}' found in ancode '" . $ancode->getId() . "'");
                     }
                     $ancode->addGrammem($this->grammems[$grammem_id]['name']);
                 } elseif ($this->isEndElement('ancode')) {
                     break;
                 }
             }
             unset($this->current);
             $this->current = $ancode;
             break;
         }
     } while ($this->read());
 }
 public function parseErrorResponse($statusCode, $content, MnsException $exception = NULL)
 {
     $this->succeed = FALSE;
     $xmlReader = new \XMLReader();
     try {
         $xmlReader->XML($content);
         while ($xmlReader->read()) {
             if ($xmlReader->nodeType == \XMLReader::ELEMENT) {
                 switch ($xmlReader->name) {
                     case Constants::ERROR:
                         $this->parseNormalErrorResponse($xmlReader);
                         break;
                     default:
                         // case Constants::Messages
                         $this->parseBatchSendErrorResponse($xmlReader);
                         break;
                 }
             }
         }
     } catch (\Exception $e) {
         if ($exception != NULL) {
             throw $exception;
         } elseif ($e instanceof MnsException) {
             throw $e;
         } else {
             throw new MnsException($statusCode, $e->getMessage());
         }
     } catch (\Throwable $t) {
         throw new MnsException($statusCode, $t->getMessage());
     }
 }
 public function parseErrorResponse($statusCode, $content, MnsException $exception = NULL)
 {
     $this->succeed = FALSE;
     $xmlReader = new \XMLReader();
     try {
         $xmlReader->XML($content);
         $result = XMLParser::parseNormalError($xmlReader);
         if ($result['Code'] == Constants::QUEUE_NOT_EXIST) {
             throw new QueueNotExistException($statusCode, $result['Message'], $exception, $result['Code'], $result['RequestId'], $result['HostId']);
         }
         if ($result['Code'] == Constants::MESSAGE_NOT_EXIST) {
             throw new MessageNotExistException($statusCode, $result['Message'], $exception, $result['Code'], $result['RequestId'], $result['HostId']);
         }
         throw new MnsException($statusCode, $result['Message'], $exception, $result['Code'], $result['RequestId'], $result['HostId']);
     } catch (\Exception $e) {
         if ($exception != NULL) {
             throw $exception;
         } elseif ($e instanceof MnsException) {
             throw $e;
         } else {
             throw new MnsException($statusCode, $e->getMessage());
         }
     } catch (\Throwable $t) {
         throw new MnsException($statusCode, $t->getMessage());
     }
 }
 public static function &buildTree($source, $mode = XMLDocument::BUILD_MODE_FROM_FILE, $ns = NULL)
 {
     if ($mode == XMLDocument::BUILD_MODE_FROM_FILE) {
         if (($content = Filesystem::getFileContent($source)) === NULL) {
             return NULL;
         }
     } else {
         if ($source == "" || $source == NULL) {
             return new xmlTree();
         }
         $content = $ns == NULL ? "<ROOT>" . $source . "</ROOT>" : "<ROOT xmlns:{$ns}=\".\">" . $source . "</ROOT>";
     }
     /*$content = ereg_replace( "&amp;", "&", $content );
     		$content = ereg_replace( "&", "&amp;", $content );*/
     //echo $content;
     $content = preg_replace("/&amp;/", "&", $content);
     $content = preg_replace("/&/", "&amp;", $content);
     $content = iconv("windows-1251", "UTF-8", $content);
     $reader = new XMLReader();
     if ($reader->XML($content)) {
         $_docTree = NULL;
         $_docTree = new xmlTree();
         self::_appendChilds($_docTree->getCurrent(), $reader, 0);
         $reader = NULL;
         return $_docTree;
     } else {
         self::raiseException(ERR_XML_INVALID_XML, $content);
         return NULL;
     }
 }
示例#13
0
 /**
  * Method to load a URI into the feed reader for parsing.
  *
  * @param   string  $uri  The URI of the feed to load. Idn uris must be passed already converted to punycode.
  *
  * @return  JFeedReader
  *
  * @since   12.3
  * @throws  InvalidArgumentException
  * @throws  RuntimeException
  */
 public function getFeed($uri)
 {
     // Create the XMLReader object.
     $reader = new XMLReader();
     // Open the URI within the stream reader.
     if (!@$reader->open($uri, null, LIBXML_NOERROR | LIBXML_ERR_NONE | LIBXML_NOWARNING)) {
         // Retry with JHttpFactory that allow using CURL and Sockets as alternative method when available
         // Adding a valid user agent string, otherwise some feed-servers returning an error
         $options = new \joomla\Registry\Registry();
         $options->set('userAgent', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:41.0) Gecko/20100101 Firefox/41.0');
         $connector = JHttpFactory::getHttp($options);
         $feed = $connector->get($uri);
         if ($feed->code != 200) {
             throw new RuntimeException('Unable to open the feed.');
         }
         // Set the value to the XMLReader parser
         if (!$reader->xml($feed->body, null, LIBXML_NOERROR | LIBXML_ERR_NONE | LIBXML_NOWARNING)) {
             throw new RuntimeException('Unable to parse the feed.');
         }
     }
     try {
         // Skip ahead to the root node.
         while ($reader->read()) {
             if ($reader->nodeType == XMLReader::ELEMENT) {
                 break;
             }
         }
     } catch (Exception $e) {
         throw new RuntimeException('Error reading feed.', $e->getCode(), $e);
     }
     // Setup the appopriate feed parser for the feed.
     $parser = $this->_fetchFeedParser($reader->name, $reader);
     return $parser->parse();
 }
示例#14
0
 private static function testXml()
 {
     $xml = new \XMLReader();
     $xml->XML(self::$TestXml);
     $xmlarray = xmlWithArray::xmlToarray($xml);
     return $xmlarray;
 }
示例#15
0
 protected function parseEntrypoints(\XMLReader $xml, InfosAbstract $object)
 {
     $property = $xml->name;
     while ($xml->read()) {
         if ($xml->nodeType == \XMLReader::END_ELEMENT && 'entrypoints' == $xml->name) {
             break;
         }
         if ($xml->nodeType == \XMLReader::ELEMENT) {
             $id = $config = '';
             $type = 'classic';
             while ($xml->moveToNextAttribute()) {
                 if ($xml->name == 'file') {
                     $id = $xml->value;
                 } else {
                     if ($xml->name == 'config') {
                         $config = $xml->value;
                     } else {
                         if ($xml->name == 'type') {
                             $type = $xml->value;
                         }
                     }
                 }
             }
             if ($id) {
                 if (strpos($id, '.php') === false) {
                     $id .= '.php';
                 }
                 $object->entrypoints[$id] = array('config' => $config, 'file' => $id, 'type' => $type);
             }
         }
     }
 }
示例#16
0
文件: factory.php 项目: grlf/eyedock
 /**
  * Method to load a URI into the feed reader for parsing.
  *
  * @param   string  $uri  The URI of the feed to load. Idn uris must be passed already converted to punycode.
  *
  * @return  JFeedReader
  *
  * @since   12.3
  * @throws  InvalidArgumentException
  * @throws  RuntimeException
  */
 public function getFeed($uri)
 {
     // Create the XMLReader object.
     $reader = new XMLReader();
     // Open the URI within the stream reader.
     if (!@$reader->open($uri, null, LIBXML_NOERROR | LIBXML_ERR_NONE | LIBXML_NOWARNING)) {
         // If allow_url_fopen is enabled
         if (ini_get('allow_url_fopen')) {
             // This is an error
             throw new RuntimeException('Unable to open the feed.');
         } else {
             // Retry with JHttpFactory that allow using CURL and Sockets as alternative method when available
             $connector = JHttpFactory::getHttp();
             $feed = $connector->get($uri);
             // Set the value to the XMLReader parser
             if (!$reader->xml($feed->body, null, LIBXML_NOERROR | LIBXML_ERR_NONE | LIBXML_NOWARNING)) {
                 throw new RuntimeException('Unable to parse the feed.');
             }
         }
     }
     try {
         // Skip ahead to the root node.
         while ($reader->read()) {
             if ($reader->nodeType == XMLReader::ELEMENT) {
                 break;
             }
         }
     } catch (Exception $e) {
         throw new RuntimeException('Error reading feed.');
     }
     // Setup the appopriate feed parser for the feed.
     $parser = $this->_fetchFeedParser($reader->name, $reader);
     return $parser->parse();
 }
示例#17
0
 public function actionFias()
 {
     $file = 'AS_ADDROBJ_20160609_c5080ba4-9f46-4b6e-aecc-72a630730b3a.XML';
     $interestingNodes = array('AOGUID');
     $xmlObject = new \XMLReader();
     $xmlObject->open($file);
     header('Content-Type: text/html; charset=utf-8');
     $i = 0;
     while ($xmlObject->read()) {
         if ($xmlObject->name == 'Object') {
             if ($xmlObject->getAttribute('IFNSFL') == '8603') {
                 // if (($xmlObject->getAttribute('PARENTGUID') == '0bf0f4ed-13f8-446e-82f6-325498808076' && $xmlObject->getAttribute('AOLEVEL') == '7') || $xmlObject->getAttribute('AOGUID') == '0bf0f4ed-13f8-446e-82f6-325498808076') {
                 $fias = new Fias();
                 $fias->AOGUID = $xmlObject->getAttribute('AOGUID');
                 $fias->OFFNAME = $xmlObject->getAttribute('OFFNAME');
                 $fias->SHORTNAME = $xmlObject->getAttribute('SHORTNAME');
                 $fias->IFNSFL = $xmlObject->getAttribute('IFNSFL');
                 $fias->AOLEVEL = $xmlObject->getAttribute('AOLEVEL');
                 $fias->PARENTGUID = $xmlObject->getAttribute('PARENTGUID');
                 if ($fias->validate()) {
                     $fias->save();
                 } else {
                     var_dump($fias->attributes);
                     var_dump($fias->getErrors());
                 }
                 //    $i++;
             }
         }
     }
     echo 'ok';
     $xmlObject->close();
 }
示例#18
0
function eol_xml_stats()
{
    $path = "http://localhost/eol_php_code/applications/content_server/resources/218.xml";
    $reader = new \XMLReader();
    $reader->open($path);
    $i = 0;
    $dist_count = 0;
    $taxa_count = 0;
    while (@$reader->read()) {
        if ($reader->nodeType == \XMLReader::ELEMENT && $reader->name == "taxon") {
            $string = $reader->readOuterXML();
            $string = str_ireplace("dc:", "dc_", $string);
            $string = str_ireplace("dwc:", "dwc_", $string);
            if ($xml = simplexml_load_string($string)) {
                $taxa_with_dist = false;
                $taxon_id = (string) $xml->dc_identifier;
                print "[{$taxon_id}]";
                foreach ($xml->dataObject as $o) {
                    if (@$o->subject == "http://rs.tdwg.org/ontology/voc/SPMInfoItems#Distribution") {
                        $dist_count++;
                        $taxa_with_dist = true;
                    }
                }
                if ($taxa_with_dist) {
                    $taxa_count++;
                }
            }
        }
    }
    print "\n\n";
    print "\n distribution: [{$dist_count}]";
    print "\n taxa with dist: [" . $taxa_count . "]";
    print "\n\n";
}
示例#19
0
 /**
  * Method to load a URI into the feed reader for parsing.
  *
  * @param   string  $uri  The URI of the feed to load.
  *
  * @return  JFeedReader
  *
  * @since   3.0
  * @throws  InvalidArgumentException
  * @throws  RuntimeException
  */
 public function getFeed($uri)
 {
     // Make sure the file exists.
     try {
         $this->http->get($uri);
     } catch (RunTimeException $e) {
         throw new InvalidArgumentException('The file ' . $uri . ' does not exist.');
     }
     // Create the XMLReader object.
     $reader = new XMLReader();
     // Open the URI within the stream reader.
     if (!@$reader->open($uri, null, LIBXML_NOERROR | LIBXML_ERR_NONE | LIBXML_NOWARNING)) {
         throw new RuntimeException('Unable to open the feed.');
     }
     try {
         // Skip ahead to the root node.
         while ($reader->read() && $reader->nodeType !== XMLReader::ELEMENT) {
         }
     } catch (Exception $e) {
         throw new RuntimeException('Error reading feed.');
     }
     // Setup the appopriate feed parser for the feed.
     $parser = $this->_fetchFeedParser($reader->name, $reader);
     return $parser->parse();
 }
示例#20
0
文件: XHTML.php 项目: robertop/phd
 public static function generateAcronymInfo($filename)
 {
     static $info;
     if ($info) {
         return $info;
     }
     if (!is_file($filename)) {
         v("Can't find acronym file (%s), skipping", $filename, E_USER_WARNING);
         return array();
     }
     $r = new \XMLReader();
     if (!$r->open($filename)) {
         v("Could not open file for accessing acronym information (%s)", $filename, E_USER_ERROR);
     }
     $acronyms = array();
     while ($r->read()) {
         if ($r->nodeType != \XMLReader::ELEMENT) {
             continue;
         }
         if ($r->name == "term") {
             $r->read();
             $k = $r->value;
             $acronyms[$k] = "";
         } else {
             if ($r->name == "simpara") {
                 $r->read();
                 $acronyms[$k] = $r->value;
             }
         }
     }
     $info = $acronyms;
     return $acronyms;
 }
示例#21
0
function isXml($filename)
{
    $xml = new XMLReader();
    $xml->open($filename);
    $xml->setParserProperty(XMLReader::VALIDATE, true);
    return $xml->isValid();
}
示例#22
0
 public function transferXmlToDb()
 {
     $reader = new \XMLReader();
     if (!$reader->open(Yii::getAlias('@webroot') . '/import/' . $this->filename, 'utf-8')) {
         throw new Exception('XML-файл не удалось найти.');
     }
     return $this->parseAndSaveData($reader);
 }
 private function createReader()
 {
     $reader = new XMLReader();
     if (false === $reader->open($this->xml_file)) {
         throw new Exception("Can`t open '{$this->xml_file}' xml file");
     }
     return $reader;
 }
示例#24
0
 /**
  * Проверка по схеме
  */
 public function validate($schemaPath)
 {
     $xr = new XMLReader();
     $xr->XML($this->toXmlStr());
     $xr->setSchema($schemaPath);
     while ($xr->read()) {
     }
 }
示例#25
0
 /**
  * Test get element returns null
  */
 public function testGetElementReturnsNull()
 {
     $filename = __DIR__ . '/../_files/documents/reader.docx.zip';
     $object = new XMLReader();
     $object->getDomFromZip($filename, '[Content_Types].xml');
     $element = $object->getElements('*')->item(0);
     $this->assertNull($object->getElement('yadayadaya', $element));
 }
示例#26
0
文件: XmlTrim.php 项目: shevron/stoa
 public function filter($value)
 {
     $this->_initReaderWriter();
     $this->_reader->XML($value);
     $this->_doXmlTrim();
     $this->_writer->endDocument();
     return $this->_writer->outputMemory();
 }
 public function rewind()
 {
     if ($this->reader->nodeType !== XMLReader::NONE) {
         throw new BadMethodCallException('Reader can not be rewound');
     }
     $this->index = 0;
     $this->valid = $this->reader->read();
 }
示例#28
0
 protected function parse()
 {
     $depth = 0;
     $elements = array();
     $elements_[$depth] =& $elements;
     while ($this->xml->read()) {
         switch ($this->xml->nodeType) {
             case XMLReader::END_ELEMENT:
                 if ($this->xml->depth - 1 < $depth) {
                     $elements =& $elements_[$depth];
                     $element =& $elements[sizeof($elements) - 1];
                     $depth = $this->xml->depth - 1;
                 }
                 break;
             case XMLReader::ATTRIBUTE:
                 # Read does not go through attributes :(
                 break;
             case XMLReader::ELEMENT:
                 if (strlen($this->xml->name) == 0) {
                     continue;
                 }
                 if ($this->xml->depth > $depth) {
                     $depth = $this->xml->depth;
                     $elements_[$depth] =& $elements;
                     $elements =& $element['elements'];
                 }
                 $elements[] = array('tag' => $this->xml->name);
                 # Working Element
                 $element =& $elements[sizeof($elements) - 1];
                 # Attributes
                 if ($this->xml->hasAttributes) {
                     $this->xml->moveToFirstAttribute();
                     $element['attributes'] = array();
                     $element['attributes'][$this->xml->name] = $this->xml->value;
                     while ($this->xml->moveToNextAttribute()) {
                         $element['attributes'][$this->xml->name] = $this->xml->value;
                     }
                 }
                 if ($this->xml->isEmptyElement) {
                     if ($this->xml->depth - 1 < $depth) {
                         $elements =& $elements_[$depth];
                         $element =& $elements[sizeof($elements) - 1];
                         $depth = $this->xml->depth - 1;
                     }
                 }
                 break;
             case XMLReader::TEXT:
             case XMLReader::CDATA:
                 if (!isset($element['value'])) {
                     $element['value'] = $this->xml->value;
                 } else {
                     $element['value'] .= $this->xml->value;
                 }
                 break;
         }
     }
     $this->elements = $elements;
 }
示例#29
0
    public function create()
    {
        $database_logs = Database_Logs::getInstance();
        Database_SQLite::exec($this->db, "PRAGMA temp_store = MEMORY;");
        Database_SQLite::exec($this->db, "PRAGMA synchronous = OFF;");
        Database_SQLite::exec($this->db, "PRAGMA journal_mode = OFF;");
        $sql = <<<'EOD'
CREATE TABLE IF NOT EXISTS morphhb (
  book integer,
  chapter integer,
  verse integer,
  hebrew text
);
EOD;
        Database_SQLite::exec($this->db, $sql);
        $books = array("Gen", "Exod", "Lev", "Num", "Deut", "Josh", "Judg", "Ruth", "1Sam", "2Sam", "1Kgs", "2Kgs", "1Chr", "2Chr", "Ezra", "Neh", "Esth", "Job", "Ps", "Prov", "Eccl", "Song", "Isa", "Jer", "Lam", "Ezek", "Dan", "Hos", "Joel", "Amos", "Obad", "Jonah", "Mic", "Nah", "Hab", "Zeph", "Hag", "Zech", "Mal");
        foreach ($books as $book => $osis) {
            $book++;
            $database_logs->log("Importing Hebrew data for {$book} {$osis}");
            $xml = new XMLReader();
            $xml->open("../morphhb/{$osis}.xml");
            $chapter = 0;
            $verse = 0;
            $word = false;
            $hebrew = "";
            while ($xml->read()) {
                $nodeType = $xml->nodeType;
                $name = $xml->name;
                if ($nodeType == XMLReader::ELEMENT) {
                    if ($name == "verse") {
                        $osisID = $xml->getAttribute("osisID");
                        $osisID = explode(".", $osisID);
                        $chapter = intval($osisID[1]);
                        $verse = intval($osisID[2]);
                    }
                    if ($name == "w") {
                        $word = true;
                    }
                }
                if ($nodeType == XMLReader::TEXT) {
                    if ($word) {
                        $hebrew = $xml->value;
                        $hebrew = trim($hebrew);
                        $hebrew = str_replace("/", "", $hebrew);
                        $hebrew = str_replace("'", "''", $hebrew);
                        $sql = "INSERT INTO morphhb (book, chapter, verse, hebrew) VALUES ({$book}, {$chapter}, {$verse}, '{$hebrew}');";
                        Database_SQLite::exec($this->db, $sql);
                    }
                }
                if ($nodeType == XMLReader::END_ELEMENT) {
                    if ($name == "w") {
                        $word = false;
                    }
                }
            }
            $xml->close();
        }
    }
示例#30
-1
 public function testParseXmlFromHttpStream()
 {
     $stream = fopen('http://www.splunk.com/', 'rb');
     $streamUri = Splunk_StreamStream::createUriForStream($stream);
     $xmlReader = new XMLReader();
     $xmlReader->open($streamUri);
 }