/** * @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 next() { $this->valid && $this->index++; if ($this->localName) { $this->valid = $this->reader->next($this->localName); } else { $this->valid = $this->reader->next(); } }
/** * @inheritdoc */ public function next() { if (!isset($this->xmlReader)) { throw new \RuntimeException('The resource needs to be open.'); } while ($this->xmlReader->next()) { $name = $this->xmlReader->name; $depth = $this->xmlReader->depth; if (1 == $depth && !in_array($name, array("", "#text"))) { break; } } }
/** * Parses a MySQL dump XML file. * * @param $source * @return Fixture * @throws \TheIconic\Fixtures\Exception\InvalidParserException */ public function parse($source) { $fixtureArray = []; $z = new \XMLReader(); $z->open($source); $doc = new \DOMDocument(); while ($z->read() && $z->name !== 'table_data') { } $tableName = $z->getAttribute('name'); $rowNum = 0; while ($z->read() && $z->name !== 'row') { } while ($z->name === 'row') { $node = simplexml_import_dom($doc->importNode($z->expand(), true)); $totalAttributes = $node->count(); for ($i = 0; $i < $totalAttributes; $i++) { foreach ($node->field[$i]->attributes() as $attribute) { $attribute = (string) $attribute; $value = (string) $node->field[$i]; $namespaces = $node->field[$i]->getNamespaces(true); if (empty($namespaces)) { $fixtureArray[$tableName][$rowNum][$attribute] = $value; } } } $rowNum++; $z->next('row'); } if (empty($fixtureArray)) { throw new InvalidParserException("It was not possible to parse the XML file: {$source}"); } return Fixture::create($fixtureArray); }
/** * @param \Closure $callback */ protected function parseFile(\Closure $callback) { while ($this->xmlr->localName == $this->node) { try { $sxe = new \SimpleXMLElement($this->xmlr->readOuterXml()); if (!$sxe instanceof \SimpleXMLElement) { throw new \Exception("node is note SimpleXMLElement"); } $callback($sxe); } catch (\RuntimeException $e) { throw new \RuntimeException($e->getMessage()); } catch (\Exception $e) { if ($this->trace) { echo sprintf("%s - %s - %s -%s\n", $e->getMessage(), $e->getFile(), $e->getLine(), $e->getTraceAsString()); } if ($this->strict) { throw new \RuntimeException($e->getMessage()); } } if ($this->debug) { break; } $this->xmlr->next($this->node); } $this->xmlr->close(); }
/** * 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'); } }
/** * filterFeed Reads the XML from the url and filters it based on the provided filter. The results are organized into an array keyed by the unqiue values of the filter. */ function filterFeed() { $reader = new XMLReader(); if (!$reader->open($this->url)) { throw new Exception("Cannot open feed from the provided URL."); } while ($reader->read()) { if ($reader->name == "product") { //get the entire product node. $xml_node = $reader->readOuterXML(); } if ($reader->name == $this->filter) { //read the values for the $this->filter node. $reader->read(); //get string/value from the node we are filtering and explode it by a delimiter. $nodeValues = []; $nodeValues = explode($this->delimiter, $reader->value); if (!empty($nodeValues[$this->index])) { $this->filteredXML[$nodeValues[$this->index]][] = $xml_node; } else { throw new Exception("The index specified does not exist."); } //Go to the next product. $reader->next("product"); } } //if the array has no items then the filtered node does not exist. if (empty($this->filteredXML)) { throw new Exception("{$this->filter} does not exist in the XML."); } }
public function streamXml() { $reader = new XMLReader(); $reader->open($this->getUrl()); while ($reader->next()) { while (!($reader->nodeType == XMLReader::ELEMENT && $reader->name == $this->getElement())) { if (!$reader->read()) { break 2; } //Break if something wrong } if ($reader->nodeType == XMLReader::ELEMENT && $reader->name == $this->getElement()) { (yield simplexml_load_string($reader->readOuterXml(), null, LIBXML_NOCDATA)); //Yield load XML to save time and pressure $reader->next(); } } }
/** * Create a new XML node. * * \param XMLReader $reader * XML reader object that will be used to create * this node. * * \param bool $validate * Whether an exception should be raised (\c true) * or not (\c false) if the current node is not valid. * * \param bool $subtrees * Whether to explore subtrees (\c true) or not (\c false). */ public function __construct(\XMLReader $reader, $validate, $subtrees) { do { // We must silence read()/next() as old PHPs (5.3.x) emit warnings // which get caught by PHPUnit and other custom error handlers // when the methods fail and this is known to cause some issues. if ($subtrees && !@$reader->read() || !$subtrees && !@$reader->next()) { $error = libxml_get_last_error(); // We reached the end of the document. // This is not an error per-se, // but it causes read() to fail anyway. // We throw a special error which gets caught // and dealt with appropriately by the caller. if ($error === false) { throw new \InvalidArgumentException('End of document'); } switch ($error->code) { case self::XML_ERR_UNKNOWN_ENCODING: case self::XML_ERR_UNSUPPORTED_ENCODING: throw new \fpoirotte\XRL\Faults\UnsupportedEncodingException(); // Internal & memory errors are too hard to recreate // and are thus excluded from code coverage analysis. // @codeCoverageIgnoreStart // Internal & memory errors are too hard to recreate // and are thus excluded from code coverage analysis. // @codeCoverageIgnoreStart case self::XML_ERR_INTERNAL_ERROR: case self::XML_ERR_NO_MEMORY: throw new \fpoirotte\XRL\Faults\InternalErrorException(); // @codeCoverageIgnoreEnd // @codeCoverageIgnoreEnd case self::XML_ERR_INVALID_CHAR: throw new \fpoirotte\XRL\Faults\InvalidCharacterException(); // Generic error handling. // Generic error handling. default: throw new \fpoirotte\XRL\Faults\NotWellFormedException(); } } if ($validate && !$reader->isValid()) { throw new \fpoirotte\XRL\Faults\InvalidXmlRpcException(); } $subtrees = true; } while ($reader->nodeType === \XMLReader::SIGNIFICANT_WHITESPACE); $fields = array('isEmptyElement', 'localName', 'namespaceURI', 'nodeType', 'value'); $this->properties = array(); foreach ($fields as $field) { $this->properties[$field] = $reader->{$field}; } $name = $reader->localName; if ($reader->namespaceURI !== '') { $name = '{' . $reader->namespaceURI . '}' . $name; } $this->properties['name'] = $name; }
/** * Tests JFeedParser::moveToClosingElement() * * @return void * * @since 12.3 */ public function testMoveToClosingElement() { // Set the XML for the internal reader and move the stream to the <root> element. $this->_reader->Xml('<root><child>foobar</child></root>'); $this->_reader->next('root'); // Ensure that the current node is "root". $this->assertEquals('root', $this->_reader->name); // Move to the closing element, which should be </root>. TestReflection::invoke($this->_instance, 'moveToClosingElement'); $this->assertEquals(XMLReader::END_ELEMENT, $this->_reader->nodeType); $this->assertEquals('root', $this->_reader->name); }
/** * Read an XML snippet from an element * * @param string $metafield Field that we will fill with the result * @throws MWException */ private function readXml($metafield = null) { $this->debug("Read top level metadata"); if (!$metafield || $this->reader->nodeType != XMLReader::ELEMENT) { return; } // @todo Find and store type of xml snippet. metadata['metadataType'] = "rdf" if (method_exists($this->reader, 'readInnerXML')) { $this->metadata[$metafield] = trim($this->reader->readInnerXML()); } else { throw new MWException("The PHP XMLReader extension does not come " . "with readInnerXML() method. Your libxml is probably out of " . "date (need 2.6.20 or later)."); } $this->reader->next(); }
public function addWikiIndex() { $z = new XMLReader(); $z->open(self::WIKIFILE); // move to the first <page /> node while ($z->read() && $z->name !== 'page') { } $time_start = microtime(true); $update = $this->client->createUpdate(); $i = 0; echo "Wait.."; // now that we're at the right depth, hop to the next <page /> until the end of the tree while ($z->name === 'page' && $i++ >= 0) { $doct = new DOMDocument(); // $node = new SimpleXMLElement($z->readOuterXML()); $node = simplexml_import_dom($doct->importNode($z->expand(), true)); // now you can use $node without going insane about parsing // var_dump($node->element_1); if (stristr($node->title, 'Category') === FALSE && stristr($node->revision->text, '#REDIRECT') === FALSE) { // echo $node->revision->contributor->id."<br />"; $doc = $update->createDocument(); $doc->id = $node->id; $doc->title = $node->title; $doc->revision = $node->revision->id; $doc->author = $node->revision->contributor->username; $doc->authorid = $node->revision->contributor->id; $doc->timestamp = $node->revision->timestamp; $doc->content = $node->revision->text; /* * if(strlen($node->id)>2) $doc->id = $node->id; else continue; if(strlen($node->title)>2) $doc->title = $node->title; else continue; if(strlen($node->revision->id)>2) $doc->revision = $node->revision->id; else continue; if(strlen($node->revision->timestamp)>2) $doc->timestamp = $node->revision->timestamp; else $doc->timestamp = ""; if(strlen($node->revision->contributor->username)>2) $doc->author = $node->revision->contributor->username; else continue; if(strlen($node->revision->contributor->id)>2) $doc->authorid = $node->revision->contributor->id; else $doc->authorid = " "; */ $update->addDocument($doc); if ($i % 1000 == 0) { $update->addCommit(); $result = $this->client->update($update); $update = $this->client->createUpdate(); } } // go to next <page /> $z->next('page'); } $time_end = microtime(true); // dividing with 60 will give the execution time in minutes other wise seconds $execution_time = ($time_end - $time_start) / 60; echo '<br /><b>Total Execution Time:</b> ' . $execution_time . ' Mins'; $update->addCommit(); $result = $this->client->update($update); return View::make('home.index'); }
/** * Scans conntent for cachedUntil and error * * @param string $content * @param int $errorCode * @param string $errorText */ protected function scanContent($content, &$errorCode, &$errorText) { $this->cachedUntil = null; $reader = new XMLReader(); $reader->xml($content); while ($reader->read()) { if ($reader->nodeType == XMLReader::ELEMENT && $reader->name == "error") { // got an error $errorText = $reader->readString(); $errorCode = intval($reader->getAttribute('code')); if ($reader->next("cachedUntil")) { $this->cachedUntil = $reader->readString(); } } else { if ($reader->nodeType == XMLReader::ELEMENT && $reader->name == "result") { // no errors, we need to read the cache time though if ($reader->next("cachedUntil")) { $this->cachedUntil = $reader->readString(); } } } } $reader->close(); }
private function insert_data_mysql($db) { $tbl = $db->query("select sigla, nome from estados"); $db->query("SET CHARACTER SET utf8"); $db->query("SET NAMES utf8"); $tbl->setFetchMode(PDO::FETCH_OBJ); while ($row = $tbl->fetch()) { // MySQL $arr_estados[mb_strtoupper(iconv("ISO-8859-1", "UTF-8", $row->nome), "UTF-8")] = $row->sigla; // PostgreSQL // $arr_estados[mb_strtoupper($row->nome, "UTF-8")] = $row->sigla; } var_dump($arr_estados); $xml = new XMLReader(); $xml->open('database/seeds/BR Localidades 2010 v1.kml'); // Salta as informações de cabeçalho, para o primeiro "registro" de dados ("Placemark") while ($xml->read() && $xml->name !== "Placemark") { } $contador = 0; $insert_ok = 0; $insert_erro = 0; $sql = $db->prepare("insert into cidades(codigo, nome, sigla_estado, longitude, latitude, altitude) values(?, ?, ?, ?, ?, ?)"); // Loop para varrer todas as ocorrências de "Placemark" while ($xml->name === "Placemark") { $node = new SimpleXMLElement($xml->readOuterXML()); $cidade = new SimpleXMLElement($node->asXML()); $nome = strval($cidade->name); // $nome = str_replace("'", "''", $nome); $sdata = $cidade->ExtendedData->SchemaData->SimpleData; $codigo = intval($sdata[9]); $sigla_estado = $arr_estados[strval($sdata[13])]; $longitude = floatval($sdata[18]); $latitude = floatval($sdata[19]); $altitude = floatval($sdata[20]); $res = $sql->execute(array($codigo, $nome, $sigla_estado, $longitude, $latitude, $altitude)); if ($res) { $insert_ok++; } else { $insert_erro++; echo $nome . " " . $codigo . " " . $sigla_estado . " " . $longitude . " " . $latitude . " " . $altitude . "<br>"; } // Salta para próximo registro $xml->next("Placemark"); } echo "Incluiu {$insert_ok} registros com sucesso<br>"; echo "Falha na inclusão de {$insert_erro} registros<br>"; }
function importXML($file) { global $opt; $xr = new XMLReader(); if (!$xr->open($file)) { $xr->close(); return; } $xr->read(); if ($xr->nodeType != XMLReader::ELEMENT) { echo 'error: First element expected, aborted' . "\n"; return; } if ($xr->name != 'gkxml') { echo 'error: First element not valid, aborted' . "\n"; return; } $startupdate = $xr->getAttribute('date'); if ($startupdate == '') { echo 'error: Date attribute not valid, aborted' . "\n"; return; } while ($xr->read() && !($xr->name == 'geokret' || $xr->name == 'moves')) { } $nRecordsCount = 0; do { if ($xr->nodeType == XMLReader::ELEMENT) { $element = $xr->expand(); switch ($xr->name) { case 'geokret': $this->importGeoKret($element); break; case 'moves': $this->importMove($element); break; } $nRecordsCount++; } } while ($xr->next()); $xr->close(); setSysConfig('geokrety_lastupdate', date($opt['db']['dateformat'], strtotime($startupdate))); }
/** * Validate XML file for syntax errors and basic node presence. * @param string $filePath * @return string */ public function validateFile($filePath) { /* @var $messageHandler C4B_ProductImport_Model_MessageHandler */ $messageHandler = Mage::getSingleton('xmlimport/messageHandler'); $result = self::VALIDATION_RESULT_OK; $nodeCount = 0; $xmlParser = xml_parser_create(); $xmlReader = new XMLReader(); try { if (!($xmlFile = fopen($filePath, 'r'))) { return self::VALIDATION_RESULT_FILE_ERROR; } while ($result == self::VALIDATION_RESULT_OK && ($readData = fread($xmlFile, 4096))) { if (!xml_parse($xmlParser, $readData, feof($xmlFile))) { $messageHandler->addErrorsForFile(basename($filePath), ' ', sprintf('XML Syntax error: %s at line %d, column %d.', xml_error_string(xml_get_error_code($xmlParser)), xml_get_current_line_number($xmlParser), xml_get_current_column_number($xmlParser))); $result = self::VALIDATION_RESULT_FILE_ERROR; } } if ($result == self::VALIDATION_RESULT_OK) { $xmlReader->open($filePath); if (!$xmlReader->next('products')) { $result = self::VALIDATION_RESULT_NO_ROOT_NODE; } else { $nodeCount = $this->_countProductNodes($xmlReader); } } } catch (Exception $e) { $messageHandler->addErrorsForFile(basename($filePath), ' ', $e->getMessage()); } $xmlReader->close(); fclose($xmlFile); xml_parser_free($xmlParser); if ($nodeCount == 0 && $result == self::VALIDATION_RESULT_OK) { $result = self::VALIDATION_RESULT_NO_PRODUCT_NODES; } else { if ($result == self::VALIDATION_RESULT_OK) { $messageHandler->addNotice("File contains {$nodeCount} product nodes"); } } return $result; }
public function next($localName = NULL) { $result = @parent::next($localName); if (false !== ($error = libxml_get_last_error())) { libxml_clear_errors(); $ex = new XmlParseException('Unable to move to next XML node'); $ex->addError(new XmlError($error->level, $error->message)); throw $ex; } if ($this->nodeType === self::DOC_TYPE) { throw new XmlParseException('Detected usage of disallowed DOCTYPE in XML source'); } if ($this->validateXmlSchema && !$this->isValid()) { $e = new XmlValidationException('XML schema validation failed'); foreach (libxml_get_errors() as $tmp) { $e->addError(new XmlError($tmp->level, $tmp->message)); } libxml_clear_errors(); throw $e; } return $result; }
/** * Move cursor to next node skipping all subtrees * @see \XMLReader::next * * @param string|void $localName The name of the next node to move to * @return bool TRUE on success or FALSE on failure * @throws \Box\Spout\Reader\Exception\XMLProcessingException If an error/warning occurred */ public function next($localName = null) { $this->useXMLInternalErrors(); $wasNextSuccessful = parent::next($localName); $this->resetXMLInternalErrorsSettingAndThrowIfXMLErrorOccured(); return $wasNextSuccessful; }
<?php echo "Test\n"; $xmlreader = new XMLReader(); $xmlreader->xml("<a><b/></a>"); $xmlreader->next(); $xmlreader2 = clone $xmlreader; $xmlreader2->next(); ?> Done
<?php $z = new XMLReader(); $z->open('names.xml'); $doc = new DOMDocument(); // move to the first <product /> node while ($z->read() && $z->name !== 'name') { } // now that we're at the right depth, hop to the next <product/> until the end of the tree while ($z->name === 'name') { echo $z->name . "<br>"; // either one should work //$node = new SimpleXMLElement($z->readOuterXML()); $node = simplexml_import_dom($doc->importNode($z->expand(), true)); // now you can use $node without going insane about parsing echo $node->fname . " " . $node->lname . "<br>"; $z->next('name'); }
/** * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns) * * @param string $pFilename * @throws PHPExcel_Reader_Exception */ public function listWorksheetInfo($pFilename) { // Check if file exists if (!file_exists($pFilename)) { throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist."); } $worksheetInfo = array(); $zipClass = PHPExcel_Settings::getZipClass(); $zip = new $zipClass(); if (!$zip->open($pFilename)) { throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! Error opening file."); } $xml = new XMLReader(); $res = $xml->open('zip://' . realpath($pFilename) . '#content.xml', null, PHPExcel_Settings::getLibXmlLoaderOptions()); $xml->setParserProperty(2, true); // Step into the first level of content of the XML $xml->read(); while ($xml->read()) { // Quickly jump through to the office:body node while ($xml->name !== 'office:body') { if ($xml->isEmptyElement) { $xml->read(); } else { $xml->next(); } } // Now read each node until we find our first table:table node while ($xml->read()) { if ($xml->name == 'table:table' && $xml->nodeType == XMLReader::ELEMENT) { $worksheetNames[] = $xml->getAttribute('table:name'); $tmpInfo = array('worksheetName' => $xml->getAttribute('table:name'), 'lastColumnLetter' => 'A', 'lastColumnIndex' => 0, 'totalRows' => 0, 'totalColumns' => 0); // Loop through each child node of the table:table element reading $currCells = 0; do { $xml->read(); if ($xml->name == 'table:table-row' && $xml->nodeType == XMLReader::ELEMENT) { $rowspan = $xml->getAttribute('table:number-rows-repeated'); $rowspan = empty($rowspan) ? 1 : $rowspan; $tmpInfo['totalRows'] += $rowspan; $tmpInfo['totalColumns'] = max($tmpInfo['totalColumns'], $currCells); $currCells = 0; // Step into the row $xml->read(); do { if ($xml->name == 'table:table-cell' && $xml->nodeType == XMLReader::ELEMENT) { if (!$xml->isEmptyElement) { $currCells++; $xml->next(); } else { $xml->read(); } } elseif ($xml->name == 'table:covered-table-cell' && $xml->nodeType == XMLReader::ELEMENT) { $mergeSize = $xml->getAttribute('table:number-columns-repeated'); $currCells += $mergeSize; $xml->read(); } } while ($xml->name != 'table:table-row'); } } while ($xml->name != 'table:table'); $tmpInfo['totalColumns'] = max($tmpInfo['totalColumns'], $currCells); $tmpInfo['lastColumnIndex'] = $tmpInfo['totalColumns'] - 1; $tmpInfo['lastColumnLetter'] = PHPExcel_Cell::stringFromColumnIndex($tmpInfo['lastColumnIndex']); $worksheetInfo[] = $tmpInfo; } } // foreach($workbookData->table as $worksheetDataSet) { // $worksheetData = $worksheetDataSet->children($namespacesContent['table']); // $worksheetDataAttributes = $worksheetDataSet->attributes($namespacesContent['table']); // // $rowIndex = 0; // foreach ($worksheetData as $key => $rowData) { // switch ($key) { // case 'table-row' : // $rowDataTableAttributes = $rowData->attributes($namespacesContent['table']); // $rowRepeats = (isset($rowDataTableAttributes['number-rows-repeated'])) ? // $rowDataTableAttributes['number-rows-repeated'] : 1; // $columnIndex = 0; // // foreach ($rowData as $key => $cellData) { // $cellDataTableAttributes = $cellData->attributes($namespacesContent['table']); // $colRepeats = (isset($cellDataTableAttributes['number-columns-repeated'])) ? // $cellDataTableAttributes['number-columns-repeated'] : 1; // $cellDataOfficeAttributes = $cellData->attributes($namespacesContent['office']); // if (isset($cellDataOfficeAttributes['value-type'])) { // $tmpInfo['lastColumnIndex'] = max($tmpInfo['lastColumnIndex'], $columnIndex + $colRepeats - 1); // $tmpInfo['totalRows'] = max($tmpInfo['totalRows'], $rowIndex + $rowRepeats); // } // $columnIndex += $colRepeats; // } // $rowIndex += $rowRepeats; // break; // } // } // // $tmpInfo['lastColumnLetter'] = PHPExcel_Cell::stringFromColumnIndex($tmpInfo['lastColumnIndex']); // $tmpInfo['totalColumns'] = $tmpInfo['lastColumnIndex'] + 1; // // } // } } return $worksheetInfo; }
public function getItems(XMLReader $reader) { $this->addLog($this->settings->name, 'Разбор и добавление товаров'); $this->items = []; $note = []; $counts = []; $genders = []; // $counter = 0; while ($reader->name === 'offer') { // print_r(strlen($reader->readOuterXML())); echo ' ' . (count($this->items) + 1) . ' ' . memory_get_usage() . ' ' . ++$counter . "\n"; $offer = @simplexml_load_string(@$reader->readOuterXML()); if ($offer === FALSE) { $reader->next('offer'); continue; } /** @var SimpleXMLElement $offer */ $item = (array) $offer->children(); if (!empty($item['attrs'])) { $item = array_merge($item, (array) $offer->attrs); } if (empty($item['categoryId'])) { $note['error']['Не указана категория товара (пропускаем)'] = ['count' => empty($note['error']['Не указана категория товара (пропускаем)']['count']) ? 1 : $note['error']['Не указана категория товара (пропускаем)']['count'] + 1]; continue; } // Для аттрибутов в теге param if (!empty($item['param'])) { if (is_array($item['param'])) { foreach ($offer->param as $param) { $item[(string) $param->attributes()->name] = (string) $param; } } } $attributes = $offer->attributes(); if (!empty($attributes)) { foreach ($attributes as $k => $v) { $item[(string) $k] = (string) $v; } } $this->items[] = $item; if (count($this->items) > 500) { $this->processItems(); $this->items = []; } // Cчетчик товаров в категории $cat_id = (string) $offer->categoryId; $gender = (string) $offer->attrs->gender; if (!empty($gender)) { if (isset($genders[$cat_id]) && !in_array($gender, $genders[$cat_id])) { $genders[$cat_id][] = $gender; } else { $genders[$cat_id][0] = $gender; } if (empty($counts[$cat_id][$gender])) { $counts[$cat_id][$gender] = 1; } else { $counts[$cat_id][$gender]++; } } else { if (empty($counts[$cat_id])) { $counts[$cat_id] = 1; } else { $counts[$cat_id]++; } } $reader->next('offer'); } if (count($this->items) > 0) { $this->processItems(); $this->items = []; } foreach ($genders as &$gender) { $gender = array_unique($gender); } $this->import->update_settings($this->settings->name, ['price_count' => serialize($counts), 'genders' => serialize($genders)]); $this->addLog($this->settings->name, $note, 'note'); return TRUE; }
public function export($v92ec19ffde05e15769b1bb3ee05ad745) { set_time_limit(0); if (!count($v92ec19ffde05e15769b1bb3ee05ad745)) { $v8be74552df93e31bbdd6b36ed74bdb6a = new selector('pages'); $v8be74552df93e31bbdd6b36ed74bdb6a->where('hierarchy')->page(0)->childs(0); $v92ec19ffde05e15769b1bb3ee05ad745 = $v8be74552df93e31bbdd6b36ed74bdb6a->result; } if (getRequest('as_file') === '0') { $ved780287e302ec3b9fd3c5e78771919f = new xmlExporter($this->getSourceName()); $ved780287e302ec3b9fd3c5e78771919f->addBranches($v92ec19ffde05e15769b1bb3ee05ad745); $result = $ved780287e302ec3b9fd3c5e78771919f->execute(); return $result->saveXML(); } $v857a5246dff0c3c79e476b004684f6d3 = "./sys-temp/export/"; $vb80bb7740288fda1f201890375a60c8f = getRequest('param0'); $v97fd815a3803a0588876bdd862014fed = $v857a5246dff0c3c79e476b004684f6d3 . $vb80bb7740288fda1f201890375a60c8f . "." . parent::getFileExt(); $v6990a54322d9232390a784c5c9247dd6 = $v857a5246dff0c3c79e476b004684f6d3 . $vb80bb7740288fda1f201890375a60c8f; if (!is_dir($v6990a54322d9232390a784c5c9247dd6)) { mkdir($v6990a54322d9232390a784c5c9247dd6, 0777, true); } if (file_exists($v97fd815a3803a0588876bdd862014fed) && !file_exists(CURRENT_WORKING_DIR . '/sys-temp/runtime-cache/' . md5($this->getSourceName()))) { unlink($v97fd815a3803a0588876bdd862014fed); } if ($v92ec19ffde05e15769b1bb3ee05ad745) { $v33030abc929f083da5f6c3f755b46034 = array('./tpls/', './xsltTpls/', './css/', './js/', './usels/', './umaps/', './templates/'); foreach ($v33030abc929f083da5f6c3f755b46034 as $v100664c6e2c0333b19a729f2f3ddb7dd) { if (is_dir($v100664c6e2c0333b19a729f2f3ddb7dd)) { $v736007832d2167baaae763fd3a3f3cf1 = new umiDirectory($v100664c6e2c0333b19a729f2f3ddb7dd); $v45b963397aa40d4a0063e0d85e4fe7a1 = $v736007832d2167baaae763fd3a3f3cf1->getAllFiles(1); foreach ($v45b963397aa40d4a0063e0d85e4fe7a1 as $vd6fe1d0be6347b8ef2427fa629c04485 => $vb068931cc450442b63f5b3d276ea4297) { $v8c7dd922ad47494fc02c388e12c00eac = new umiFile($vd6fe1d0be6347b8ef2427fa629c04485); if (!is_dir($v6990a54322d9232390a784c5c9247dd6 . ltrim($v8c7dd922ad47494fc02c388e12c00eac->getDirName(), '.'))) { mkdir($v6990a54322d9232390a784c5c9247dd6 . ltrim($v8c7dd922ad47494fc02c388e12c00eac->getDirName(), '.'), 0777, true); } copy($v8c7dd922ad47494fc02c388e12c00eac->getFilePath(), $v6990a54322d9232390a784c5c9247dd6 . $v8c7dd922ad47494fc02c388e12c00eac->getFilePath(true)); } } } } $v71b70dd1e455c477220693d84ccd5682 = $v97fd815a3803a0588876bdd862014fed . '.tmp'; $v480d1b61a0432d1319f7504a3d7318dd = (int) mainConfiguration::getInstance()->get("modules", "exchange.export.limit"); if ($v480d1b61a0432d1319f7504a3d7318dd <= 0) { $v480d1b61a0432d1319f7504a3d7318dd = 25; } $ved780287e302ec3b9fd3c5e78771919f = new xmlExporter($this->getSourceName(), $v480d1b61a0432d1319f7504a3d7318dd); $ved780287e302ec3b9fd3c5e78771919f->addBranches($v92ec19ffde05e15769b1bb3ee05ad745); $vdd988cfd769c9f7fbd795a0f5da8e751 = $ved780287e302ec3b9fd3c5e78771919f->execute(); if (file_exists($v97fd815a3803a0588876bdd862014fed)) { $v1de9b0a30075ae8c303eb420c103c320 = new XMLReader(); $va82feee3cc1af8bcabda979e8775ef0f = new XMLWriter(); $v1de9b0a30075ae8c303eb420c103c320->open($v97fd815a3803a0588876bdd862014fed); $va82feee3cc1af8bcabda979e8775ef0f->openURI($v71b70dd1e455c477220693d84ccd5682); $va82feee3cc1af8bcabda979e8775ef0f->startDocument('1.0', 'utf-8'); $va82feee3cc1af8bcabda979e8775ef0f->startElement('umidump'); $va82feee3cc1af8bcabda979e8775ef0f->writeAttribute('version', '2.0'); $va82feee3cc1af8bcabda979e8775ef0f->writeAttribute('xmlns:xlink', 'http://www.w3.org/TR/xlink'); $v7aa28ed115707345d0274032757e8991 = $v1de9b0a30075ae8c303eb420c103c320->read(); while ($v7aa28ed115707345d0274032757e8991) { if ($v1de9b0a30075ae8c303eb420c103c320->nodeType == XMLReader::ELEMENT) { $ve24455211a964330063a18670d943835 = $v1de9b0a30075ae8c303eb420c103c320->name; if ($ve24455211a964330063a18670d943835 != 'umidump') { $va82feee3cc1af8bcabda979e8775ef0f->startElement($ve24455211a964330063a18670d943835); if ($ve24455211a964330063a18670d943835 != 'meta') { if (!$v1de9b0a30075ae8c303eb420c103c320->isEmptyElement) { $v7852ddca47412c0d947ebf27eb83ed3a = $v1de9b0a30075ae8c303eb420c103c320->read(); while ($v7852ddca47412c0d947ebf27eb83ed3a) { if ($v1de9b0a30075ae8c303eb420c103c320->nodeType == XMLReader::ELEMENT) { $vcf7f5c76225a101e6320a96c02f92fc1 = $v1de9b0a30075ae8c303eb420c103c320->name; $va82feee3cc1af8bcabda979e8775ef0f->writeRaw($v1de9b0a30075ae8c303eb420c103c320->readOuterXML()); $v7852ddca47412c0d947ebf27eb83ed3a = $v1de9b0a30075ae8c303eb420c103c320->next(); } elseif ($v1de9b0a30075ae8c303eb420c103c320->nodeType == XMLReader::END_ELEMENT && $v1de9b0a30075ae8c303eb420c103c320->name == $ve24455211a964330063a18670d943835) { $v7852ddca47412c0d947ebf27eb83ed3a = false; } else { $v7852ddca47412c0d947ebf27eb83ed3a = $v1de9b0a30075ae8c303eb420c103c320->next(); } } } if ($vdd988cfd769c9f7fbd795a0f5da8e751->getElementsByTagName($ve24455211a964330063a18670d943835)->item(0)->hasChildNodes()) { $v268184c12df027f536154d099d497b31 = $vdd988cfd769c9f7fbd795a0f5da8e751->getElementsByTagName($ve24455211a964330063a18670d943835)->item(0)->childNodes; foreach ($v268184c12df027f536154d099d497b31 as $v1b7d5726533ab525a8760351e9b5e415) { $va5e171f642af8e3bd24c50cdc4d66fe3 = new DOMDocument(); $va5e171f642af8e3bd24c50cdc4d66fe3->formatOutput = true; $v36c4536996ca5615dcf9911f068786dc = $va5e171f642af8e3bd24c50cdc4d66fe3->importNode($v1b7d5726533ab525a8760351e9b5e415, true); $va5e171f642af8e3bd24c50cdc4d66fe3->appendChild($v36c4536996ca5615dcf9911f068786dc); $va82feee3cc1af8bcabda979e8775ef0f->writeRaw($va5e171f642af8e3bd24c50cdc4d66fe3->saveXML($v36c4536996ca5615dcf9911f068786dc, LIBXML_NOXMLDECL)); } } } elseif ($ve24455211a964330063a18670d943835 == 'meta') { $va82feee3cc1af8bcabda979e8775ef0f->writeRaw($v1de9b0a30075ae8c303eb420c103c320->readInnerXML()); $v92ec19ffde05e15769b1bb3ee05ad745 = $vdd988cfd769c9f7fbd795a0f5da8e751->getElementsByTagName('branches'); if ($v92ec19ffde05e15769b1bb3ee05ad745->item(0)) { $va82feee3cc1af8bcabda979e8775ef0f->writeRaw($vdd988cfd769c9f7fbd795a0f5da8e751->saveXML($v92ec19ffde05e15769b1bb3ee05ad745->item(0), LIBXML_NOXMLDECL)); } } $va82feee3cc1af8bcabda979e8775ef0f->fullEndElement(); $v7aa28ed115707345d0274032757e8991 = $v1de9b0a30075ae8c303eb420c103c320->next(); continue; } } $v7aa28ed115707345d0274032757e8991 = $v1de9b0a30075ae8c303eb420c103c320->read(); } $va82feee3cc1af8bcabda979e8775ef0f->fullEndElement(); $v1de9b0a30075ae8c303eb420c103c320->close(); $va82feee3cc1af8bcabda979e8775ef0f->endDocument(); $va82feee3cc1af8bcabda979e8775ef0f->flush(); unlink($v97fd815a3803a0588876bdd862014fed); rename($v71b70dd1e455c477220693d84ccd5682, $v97fd815a3803a0588876bdd862014fed); } else { file_put_contents($v97fd815a3803a0588876bdd862014fed, $vdd988cfd769c9f7fbd795a0f5da8e751->saveXML()); } $this->completed = $ved780287e302ec3b9fd3c5e78771919f->isCompleted(); return false; }
$feeds = array(); $doc = new DOMDocument(); require_once 'models/feed.php'; function x_attribute($object, $attribute) { if (isset($object[$attribute])) { return (string) $object[$attribute]; } } while ($z->read() && $z->name !== 'source') { } while ($z->name === 'source') { $node = new SimpleXMLElement($z->readOuterXML()); $feed = new Feed(); $feed->setTitle($node->title); $feed->setURL($node->feed_url); $feed->setPicture($node->picture); $feeds[] = $feed; if (!file_exists('xml/feeds/' . $feed->title . '.xml')) { file_put_contents('xml/feeds/' . $feed->title . ".xml", file_get_contents($feed->feed_url)); } else { $ttl = 1800; $age = time() - filemtime('xml/feeds/' . $feed->title . '.xml'); if ($age >= $ttl) { unlink('xml/feeds/' . $feed->title . '.xml'); file_put_contents('xml/feeds/' . $feed->title . ".xml", file_get_contents($feed->feed_url)); } } $z->next('source'); } include 'getimportantposts.php';
function loadXML($xmlLocation) { $services = array(); // Read in the XML $xml = new \XMLReader(); $xml->open($xmlLocation); // Move to the first "record" node while ($xml->read() && $xml->name !== 'record') { } // Iterate through each "record" until the end of the tree while ($xml->name === 'record') { // Import the node into a simple XML element $service = new \SimpleXMLElement($xml->readOuterXML()); $xml->next('record'); $services[(string) $service->protocol][(string) $service->number] = (string) $service->description; } return $services; }
/** * {@inheritdoc} */ public function next() { ++$this->position; $this->reader->next('product'); }
public function player_enc($sport='',$filenum=''){ //$this->output->enable_profiler(TRUE); $debug=true; if(empty($sport))$sport=strtolower($this->uri->segment(3)); if(empty($filenum))$filenum=strtolower($this->uri->segment(4)); if(!empty($sport)){ if($sport=="nfl"){ if(empty($filenum)) exit; $filename="NFL_PLAYER_ENC\$".$filenum.".XML"; $url=$this->statspath.$filename; $layer1="nfl-player-encyclopedia"; $layer2="nfl-player-encyclopedia-year"; $career="nfl-player-encyclopedia-career"; $categories=array( "games"=>"nfl-player-encyclopedia-games", "offense"=>"nfl-player-encyclopedia-offense", "defense"=>"nfl-player-encyclopedia-defense", "misc"=>"nfl-player-encyclopedia-miscellaneous", "kicking"=>"nfl-player-encyclopedia-kicking", "punting"=>"nfl-player-encyclopedia-punting", "returning"=>"nfl-player-encyclopedia-returning", "offline"=>"nfl-player-encyclopedia-off-line", "fumbles"=>"nfl-player-encyclopedia-fumbles", ); }elseif($sport=="nba"){ $filename="NBA_PLAYER_ENC.XML"; $url=$this->statspath.$filename; $layer1="nba-player-encyclopedia"; $layer2="nba-player-encyclopedia-year"; $career="nba-player-encyclopedia-career"; $skip=array("team-name","team-city","team-code"); }elseif($sport=="cbk"){ if(empty($filenum)) exit; $filename="CBK_PLAYER_ENC\$".$filenum.".XML"; $url=$this->statspath.$filename; $layer1="cbk-player-encyclopedia"; $layer2="cbk-player-encyclopedia-year"; $career="cbk-player-encyclopedia-career"; $skip=array("team-name","team-city","team-code"); }elseif($sport=="cfb"){ if(empty($filenum)) exit; $filename="CFB_PLAYER_ENC\$".$filenum.".XML"; $url=$this->statspath.$filename; $layer1="cfb-player-encyclopedia"; $layer2="cfb-player-encyclopedia-year"; $career="cfb-player-encyclopedia-career"; $skip=array("team-name","team-city","team-code"); }elseif($sport=="nhl"){ if(empty($filenum)) exit; $filename="NHL_PLAYER_ENC\$".$filenum.".XML"; $url=$this->statspath.$filename; $layer1="nhl-player-encyclopedia"; $layer2="nhl-player-encyclopedia-year"; $career="nhl-player-encyclopedia-career"; $categories=array( "skating"=>"nhl-skating-stats", "goaltending"=>"nhl-goaltending-stats", ); $skip=array("team-name","team-city","team-code","sequence"); //DELETE FROM `ci_sport_player_career` WHERE `player_id` IN (301772,301769,543573,225414,296021,231130,178023,329643,550521,386807,170695,542954,392942,184268,549269,504293,170560,600117,171423,547716,330276,268149,504313,564333,607591,229378,172508,610878,544288,496357,329563) }elseif($sport=="mlb"){ if(empty($filenum)) exit; $filename="MLB_PLAYER_ENC\$".$filenum.".XML"; $url=$this->statspath.$filename; $layer1="baseball-mlb-player-encyclopedia"; $layer2="baseball-mlb-player-encyclopedia-year"; $career=false; $categories=array( "hitting"=>"baseball-mlb-player-encyclopedia-hitting", "pitching"=>"baseball-mlb-player-encyclopedia-pitching", "fielding"=>"baseball-mlb-player-encyclopedia-fielding", ); $skip=array("team-name","team-city","team-code","sequence"); }elseif($sport=="golf"){ $filename="GOLF_GOLFER_ENC_PGA.XML"; $url=$this->statspath.$filename; $layer1="golfer-encyclopedia"; $layer2="golfer-encyclopedia-year"; $career="golfer-encyclopedia-career"; $skip=array(); } echo ($debug)?"<a href='".site_url("statsfeed/".$filename)."'>XML</a>":""; $XMLReader = new XMLReader; $xml_file_path=$this->statspath.$filename; $XMLReader->open($xml_file_path); $player_ids=array(); while ($XMLReader->read() && $XMLReader->name !==$layer1); while ($XMLReader->name === $layer1) { $node = new SimpleXMLElement($XMLReader->readOuterXML()); if($sport=='golf'){ $player_id=(int)$node->{'golfer-code'}->attributes()->{'global-id'}; }else{ $player_id=(int)$node->{'player-code'}->attributes()->{'global-id'}; } //Delete this user's existing data $this->db->where('player_id',$player_id); $this->db->delete('sport_player_career'); //Create a temporary csv file $csv_path=$this->uploadpath.$player_id.".csv"; $handle=fopen($csv_path,"c"); echo ($debug)?"<hr><h1 style='background:green;color:white;margin:0;padding:.25em;'>PLAYER_ID: ".$player_id."</h1>":""; $player_ids[]=$player_id; foreach($node->{$layer2} as $yearly){ //echo "<pre>".print_r($yearly,true)."</pre>"; $year=$yearly->attributes()->year; if(isset($yearly->{'team-code'})) $team_id=$yearly->{'team-code'}->attributes()->{'global-id'}; else $team_id=0; echo ($debug)?"<h2 style='background:yellow;margin:0;padding:.25em;'>YEAR: ".$year." - TEAM: ".$team_id."</h2>":""; if($sport=="nfl" || $sport=="nhl" || $sport=="mlb"){ foreach($categories as $category=>$catkey){ if($catkey!=false){ if(isset($yearly->{$catkey})){ $cats=$yearly->{$catkey}; echo ($debug)?"<h3 style='background:grey;margin:0;padding:.25em;'>CATEGORY: ".$category."</h3>":""; foreach($cats as $catstats){ //echo "<pre>".print_r($atts,true)."</pre>"; foreach($catstats as $key=>$atts){ foreach($atts->attributes() as $key2=>$value){ $uglykeycheck=explode('-',$key); if($key!=$key2 && $uglykeycheck[count($uglykeycheck)-1]!=$key2) $k=$key."-".$key2; else $k=$key; $value=(float)$value; $insert=array( "player_id"=>$player_id, "sport"=>$sport, "year"=>$year, "team_id"=>$team_id, "category"=>$category, "statkey"=>$k, "statvalue"=>$value ); fputcsv($handle, $insert); //echo ($debug)?"<h4>(1) ".$k." : ".$value."</h4>":""; } } } } } } }else{ foreach($yearly as $key1=>$y){ if(!in_array($key1,$skip)){ //echo ($debug)?"<h3 style='background:grey;margin:0;padding:.25em;'>CATEGORY: ".$category."</h3>":""; //echo ($debug)?"<h4>".$key1."</h4><pre>".print_r($y,true)."</pre>":""; if(is_array($y)){ foreach($y as $key15=>$y2){ foreach($y->attributes() as $key2=>$value){ $uglykeycheck=explode('-',$key1); if($key1!=$key2 && $key2 != $key15 && $uglykeycheck[count($uglykeycheck)-1]!=$key2) $k=$key1."-".$key15."-".$key2; elseif($key1!=$key2 && $key2 == $key15 && $uglykeycheck[count($uglykeycheck)-1]!=$key2) $k=$key1."-".$key2; elseif($key1!=$key2 && $key1 == $key15 && $uglykeycheck[count($uglykeycheck)-1]!=$key2) $k=$key15."-".$key2; elseif($key1!=$key2 && $uglykeycheck[count($uglykeycheck)-1]!=$key2) $k=$key1."-".$key2; else $k=$key1; $value=(float)$value; $insert=array( "player_id"=>$player_id, "sport"=>$sport, "year"=>$year, "team_id"=>$team_id, "category"=>"n/a", "statkey"=>$k, "statvalue"=>$value ); fputcsv($handle, $insert); //echo ($debug)?"<h4>(2) ".$k." : ".$value."</h4>":""; } } }else{ foreach($y->attributes() as $key2=>$value){ $uglykeycheck=explode('-',$key1); if($key1!=$key2 && $uglykeycheck[count($uglykeycheck)-1]!=$key2) $k=$key1."-".$key2; else $k=$key1; $value=(float)$value; $insert=array( "player_id"=>$player_id, "sport"=>$sport, "year"=>$year, "team_id"=>$team_id, "category"=>"n/a", "statkey"=>$k, "statvalue"=>$value ); fputcsv($handle, $insert); //echo ($debug)?"<h4>(3) ".$k." : ".$value."</h4>":""; } } } } } } //Get the career stats here if($career !== false && isset($node->{$career})){ $cats=$node->{$career}; $category="career"; echo ($debug)?"<h2 style='background:yellow;margin:0;padding:.25em;'>CAREER</h2>":""; //echo ($debug)?"<pre>".print_r($cats,true)."</pre>":""; if($sport=="nfl" || $sport=="nhl"){ foreach($categories as $category=>$catkey){ if($catkey!=false){ $cats=$node->{$career}->{$catkey}; echo ($debug)?"<h3 style='background:grey;margin:0;padding:.25em;'>CATEGORY: ".$category."</h3>":""; //echo "<pre>".print_r($cats,true)."</pre>"; foreach($cats as $catstats){ //echo "<pre>".print_r($atts,true)."</pre>"; foreach($catstats as $key=>$atts){ foreach($atts->attributes() as $key2=>$value){ $uglykeycheck=explode('-',$key); if($key!=$key2 && $uglykeycheck[count($uglykeycheck)-1]!=$key2) $k=$key."-".$key2; else $k=$key; $value=(float)$value; $insert=array( "player_id"=>$player_id, "sport"=>$sport, "year"=>0, "team_id"=>$team_id, "category"=>$category, "statkey"=>$k, "statvalue"=>$value ); fputcsv($handle, $insert); //echo ($debug)?"<h4>(4) ".$k." : ".$value."</h4>":""; } } } } } }else{ foreach($cats as $catstats){ foreach($catstats as $key1=>$y) if(!in_array($key1,$skip)){ //echo ($debug)?"<h3 style='background:grey;margin:0;padding:.25em;'>CATEGORY: ".$category."</h3>":""; foreach($y->attributes() as $key2=>$value){ $uglykeycheck=explode('-',$key1); if($key1!=$key2 && $uglykeycheck[count($uglykeycheck)-1]!=$key2) $k=$key1."-".$key2; else $k=$key1; $value=(float)$value; $insert=array( "player_id"=>$player_id, "sport"=>$sport, "year"=>0, "team_id"=>$team_id, "category"=>$category, "statkey"=>$k, "statvalue"=>$value ); fputcsv($handle, $insert); echo ($debug)?"<h4>(5) ".$k." : ".$value."</h4>":""; } } } } } fclose($handle); //exit; $command="mysql -u".$this->db->username." -p".$this->db->password." -e\"LOAD DATA LOCAL INFILE '".$csv_path."' ". "INTO TABLE ".$this->db->dbprefix('sport_player_career')." ". "FIELDS TERMINATED BY ',' ". "LINES TERMINATED BY '".htmlspecialchars('\\')."n' ". "(player_id, sport, year, team_id, category, statkey, statvalue);\" ".$this->db->database; //echo $command; $execresult=exec($command); //var_dump($execresult); //exit; unlink($csv_path); $XMLReader->next($layer1); } echo ($debug)?implode(',',$player_ids):""; $this->update_log($filename); } }
/** * Get the value of the CreateDateAndTime node from the XML in the given file. * If the node doesn't exist in the file, will return null. * @param string $filename path to XML file * @return string|null */ protected function _getDateTimeFromFeed($filename) { $reader = new XMLReader(); $reader->open($filename); // the following 2 variables prevent the edge case where we get a large file // with a node depth < 2 $elementsRead = 0; $maxElements = 2; // the date/time node is at depth 2 $targetDepth = 2; // navigate to within the message header while ($reader->depth < $targetDepth && $elementsRead <= $maxElements && $reader->read()) { // ignore whitespace if ($reader->nodeType !== XMLReader::ELEMENT) { continue; } } $dateNode = null; // at this point we should be at the depth where the creation date is. // if we stopped on the node, then grab it if ($reader->localName === 'CreateDateAndTime') { $dateNode = $reader->expand(); } elseif ($reader->next('CreateDateAndTime')) { // otherwise go to the next instance of it $dateNode = $reader->expand(); } return $dateNode ? $dateNode->nodeValue : null; }
/** * @dataProvider fromXmlDataProvider */ public function testFromXmlReader(callable $buildDoc, callable $buildMeta, callable $validate) { /** @var \DOMDocument $doc */ $doc = $buildDoc(); /** @var XmlMetaInterface $meta */ $meta = $buildMeta(); $xml = new \XMLReader(); $xml->XML($doc->saveXML()); $xml->next(); $instance = $meta->fromXml($xml); $validate($instance); }
/** * @param $xmlFilePath * @return \Generator|Product[] */ public function readFromPath($xmlFilePath) { $xml = new \XMLReader(); $xml->open($xmlFilePath); while ($xml->read() && $xml->name !== 'product') { } $decoder = new XmlDecoder(); while ($xmlData = $xml->readOuterXml()) { (yield $decoder->decodeProduct(new \SimpleXMLElement($xmlData))); $xml->next('product'); } $xml->close(); }