/** * @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(); }
public static function generateVersionInfo($filename) { static $info; if ($info) { return $info; } if (!is_file($filename)) { v("Can't find Version information file (%s), skipping!", $filename, E_USER_WARNING); return array(); } $r = new \XMLReader(); if (!$r->open($filename)) { v("Can't open the version info file (%s)", $filename, E_USER_ERROR); } $versions = array(); while ($r->read()) { if ($r->moveToAttribute("name") && ($funcname = str_replace(array("::", "->", "__", "_", '$'), array("-", "-", "-", "-", ""), $r->value)) && $r->moveToAttribute("from") && ($from = $r->value)) { $versions[strtolower($funcname)] = $from; $r->moveToElement(); } } $r->close(); $info = $versions; return $versions; }
function getClioNum($appurl, $link) { $clio = $current = $currentA = ""; $reader = new XMLReader(); $clioQ = $appurl . '/getSingleStuff.xq?doc=' . $link . '_ead.xml§ion=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; }
/** * @inheritdoc */ protected function doRewind() { $this->reader->close(); $this->open($this->resource->getFile()->getPathname()); $this->key = -1; $this->next(); }
/** * Parse the passed in Sparql XML string into a more easily usable format. * * @param string $sparql * A string containing Sparql result XML. * * @return array * Indexed (numerical) array, containing a number of associative arrays, * with keys being the same as the variable names in the query. * URIs beginning with 'info:fedora/' will have this beginning stripped * off, to facilitate their use as PIDs. */ public static function parseSparqlResults($sparql) { // Load the results into a XMLReader Object. $xmlReader = new XMLReader(); $xmlReader->xml($sparql); // Storage. $results = array(); // Build the results. while ($xmlReader->read()) { if ($xmlReader->localName === 'result') { if ($xmlReader->nodeType == XMLReader::ELEMENT) { // Initialize a single result. $r = array(); } elseif ($xmlReader->nodeType == XMLReader::END_ELEMENT) { // Add result to results $results[] = $r; } } elseif ($xmlReader->nodeType == XMLReader::ELEMENT && $xmlReader->depth == 3) { $val = array(); $uri = $xmlReader->getAttribute('uri'); if ($uri !== NULL) { $val['value'] = self::pidUriToBarePid($uri); $val['uri'] = (string) $uri; $val['type'] = 'pid'; } else { //deal with any other types $val['type'] = 'literal'; $val['value'] = (string) $xmlReader->readInnerXML(); } $r[$xmlReader->localName] = $val; } } $xmlReader->close(); return $results; }
/** * @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 parse($file) { $this->currentFile = new \SplFileObject($file); $this->path = []; $this->xmlReader->open($file); $this->read(); $this->xmlReader->close(); }
/** * Parse a beer XML, returning an array of the record objects found * * @param string $xml * @return IRecipe[]|IEquipment[]|IFermentable[]|IHop[]|IMashProfile[]|IMisc[]|IStyle[]|IWater[]|IYeast[] */ public function parse($xml) { $this->xmlReader->XML($xml); $records = array(); while ($this->xmlReader->read()) { // Find records if ($this->xmlReader->nodeType == \XMLReader::ELEMENT && isset($this->tagParsers[$this->xmlReader->name])) { $recordParser = new $this->tagParsers[$this->xmlReader->name](); /** @var $recordParser Record */ $recordParser->setXmlReader($this->xmlReader); $recordParser->setRecordFactory($this->recordFactory); $records[] = $recordParser->parse(); } } $this->xmlReader->close(); return $records; }
/** * @inheritdoc */ public function close() { if (!isset($this->xmlReader)) { throw new \RuntimeException('The resource needs to be open.'); } $this->xmlReader->close(); unset($this->xmlReader); }
/** * {@inheritdoc} */ public function rewind() { if ($this->xml) { $this->xml->close(); } $this->xml = new \XMLReader(); $this->xml->open($this->path); $this->next(); }
/** * Asserts that the xml reader is at the final closing tag of an xml file and * closes the reader. * * @param $tag string: (optional) the name of the final tag * (e.g.: "mediawiki" for </mediawiki>) */ protected function assertDumpEnd($name = "mediawiki") { $this->assertNodeEnd($name, false); if ($this->xml->read()) { $this->skipWhitespace(); } $this->assertEquals($this->xml->nodeType, XMLReader::NONE, "No proper entity left to parse"); $this->xml->close(); }
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))); }
/** * Creates a Map of devices from the xml file * * @param string $fileName path to the xml file to parse * @return Map of <deviceId ModelDevice> */ public static function parse($fileName, $validationSchema) { $devicesMap = array(); $deviceID = null; $groupID = null; $reader = new XMLReader(); $reader->open($fileName); $fullFileName = dirname(__FILE__) . DIRECTORY_SEPARATOR . $validationSchema; $reader->setRelaxNGSchema($fullFileName); libxml_use_internal_errors(TRUE); while ($reader->read()) { if (!$reader->isValid()) { throw new Exception(libxml_get_last_error()->message); } $nodeName = $reader->name; switch ($reader->nodeType) { case XMLReader::ELEMENT: switch ($nodeName) { case WURFL_Xml_Interface::DEVICE: $groupIDCapabilitiesMap = array(); $deviceID = $reader->getAttribute(WURFL_Xml_Interface::ID); $userAgent = $reader->getAttribute(WURFL_Xml_Interface::USER_AGENT); $fallBack = $reader->getAttribute(WURFL_Xml_Interface::FALL_BACK); $actualDeviceRoot = $reader->getAttribute(WURFL_Xml_Interface::ACTUAL_DEVICE_ROOT); $currentCapabilityNameValue = array(); if ($reader->isEmptyElement) { $device = new WURFL_Xml_ModelDevice($deviceID, $userAgent, $fallBack, $actualDeviceRoot); $devicesMap[$deviceID] = $device; } break; case WURFL_Xml_Interface::GROUP: $groupID = $reader->getAttribute(WURFL_Xml_Interface::GROUP_ID); $groupIDCapabilitiesMap[$groupID] = array(); break; case WURFL_Xml_Interface::CAPABILITY: $capabilityName = $reader->getAttribute(WURFL_Xml_Interface::CAPABILITY_NAME); $capabilityValue = $reader->getAttribute(WURFL_Xml_Interface::CAPABILITY_VALUE); $currentCapabilityNameValue[$capabilityName] = $capabilityValue; $groupIDCapabilitiesMap[$groupID][$capabilityName] = $capabilityValue; break; } break; case XMLReader::END_ELEMENT: if ($nodeName == WURFL_Xml_Interface::DEVICE) { $device = new WURFL_Xml_ModelDevice($deviceID, $userAgent, $fallBack, $actualDeviceRoot, $groupIDCapabilitiesMap); $devicesMap[$device->id] = $device; } break; } } // end of while $reader->close(); return $devicesMap; }
public static function Decode($XMLResponse, &$isFault) { $responseXML = null; try { if (empty($XMLResponse)) { throw new Exception("Given Response is not a valid SOAP response."); } $xmlDoc = new XMLReader(); $res = $xmlDoc->XML($XMLResponse); if ($res) { $xmlDoc->read(); $responseXML = $xmlDoc->readOuterXml(); $xmlDOM = new DOMDocument(); $xmlDOM->loadXML($responseXML); $isFault = trim(strtoupper($xmlDoc->localName)) == self::$FaultMessage; if ($isFault) { $xmlDOM->loadXML($xmlDoc->readOuterXml()); } switch ($xmlDoc->nodeType) { case XMLReader::ELEMENT: $nodeName = $xmlDoc->localName; $prefix = $xmlDoc->prefix; if (class_exists($nodeName)) { $xmlNodes = $xmlDOM->getElementsByTagName($nodeName); foreach ($xmlNodes as $xmlNode) { //$xmlNode->prefix = ""; $xmlNode->setAttribute("_class", $nodeName); $xmlNode->setAttribute("_type", "object"); } } break; } $responseXML = $xmlDOM->saveXML(); $unserializer = new XML_Unserializer(); $unserializer->setOption(XML_UNSERIALIZER_OPTION_COMPLEXTYPE, 'object'); $res = $unserializer->unserialize($responseXML, false); if ($res) { $responseXML = $unserializer->getUnserializedData(); } $xmlDoc->close(); } else { throw new Exception("Given Response is not a valid XML response."); } } catch (Exception $ex) { throw new Exception("Error occurred while XML decoding"); } return $responseXML; }
/** * Returns a simple array containing the title and description of a report. Static so you don't have to load the full report object to get this * information. */ public static function loadMetadata($report) { $reader = new XMLReader(); if ($reader->open($report) === false) { throw new Exception("Report {$report} could not be opened."); } $metadata = array(); while ($reader->read()) { if ($reader->nodeType == XMLREADER::ELEMENT && $reader->name == 'report') { $metadata['title'] = $reader->getAttribute('title'); $metadata['description'] = $reader->getAttribute('description'); break; } } $reader->close(); return $metadata; }
function get_locale($xml) { $reader = new XMLReader(); if (false === $reader->open($xml)) { return false; } while ($reader->read()) { if ($reader->nodeType == XMLReader::ELEMENT) { if ($reader->localName === 'locale') { $result = $reader->getAttribute('name'); $result = strlen($result) ? $result : false; break; } } } $reader->close(); return $result; }
/** * Read the SVG * @throws MWException * @return bool */ protected function read() { $keepReading = $this->reader->read(); /* Skip until first element */ while ($keepReading && $this->reader->nodeType != XMLReader::ELEMENT) { $keepReading = $this->reader->read(); } if ($this->reader->localName != 'svg' || $this->reader->namespaceURI != self::NS_SVG) { throw new MWException("Expected <svg> tag, got " . $this->reader->localName . " in NS " . $this->reader->namespaceURI); } $this->debug("<svg> tag is correct."); $this->handleSVGAttribs(); $exitDepth = $this->reader->depth; $keepReading = $this->reader->read(); while ($keepReading) { $tag = $this->reader->localName; $type = $this->reader->nodeType; $isSVG = $this->reader->namespaceURI == self::NS_SVG; $this->debug("{$tag}"); if ($isSVG && $tag == 'svg' && $type == XMLReader::END_ELEMENT && $this->reader->depth <= $exitDepth) { break; } elseif ($isSVG && $tag == 'title') { $this->readField($tag, 'title'); } elseif ($isSVG && $tag == 'desc') { $this->readField($tag, 'description'); } elseif ($isSVG && $tag == 'metadata' && $type == XMLReader::ELEMENT) { $this->readXml($tag, 'metadata'); } elseif ($isSVG && $tag == 'script') { // We normally do not allow scripted svgs. // However its possible to configure MW to let them // in, and such files should be considered animated. $this->metadata['animated'] = true; } elseif ($tag !== '#text') { $this->debug("Unhandled top-level XML tag {$tag}"); // Recurse into children of current tag, looking for animation and languages. $this->animateFilterAndLang($tag); } // Goto next element, which is sibling of current (Skip children). $keepReading = $this->reader->next(); } $this->reader->close(); $this->metadata['translations'] = $this->languages + $this->languagePrefixes; return true; }
/** * Implements the parser loop by iterating the XML stream until it finds the * required XML node type. * * @param string $path The XML file to parse. * @throws XMLStreamItemExtractorException */ public function parse($path) { set_error_handler(array($this, 'errorHandler')); try { $this->reader = $this->getReader($path); while ($this->reader->localName == $this->itemName || $this->reader->read()) { if ($this->reader->localName != $this->itemName) { continue; } $this->parseItem(); } restore_error_handler(); $this->reader->close(); } catch (XMLStreamItemExtractorException $e) { restore_error_handler(); $this->reader->close(); throw $e; } }
public function show_weather() { $citycode = '1252376'; $temptype = 'c'; $url = 'http://xml.weather.yahoo.com/forecastrss?w=' . $citycode . '&u=' . $temptype; //$xml = file_get_contents($url); $reader = new \XMLReader(); $reader->open($url, 'utf-8'); while ($reader->read()) { if ($reader->name == 'yweather:condition') { $code = $reader->getAttribute('code'); //获取天气代码 $temp = $reader->getAttribute('temp'); //获取温度 } if ($reader->name == 'yweather:atmosphere') { $humi = $reader->getAttribute('humidity'); //获取湿度 } if ($reader->name == 'yweather:wind') { $wind = $reader->getAttribute('speed'); //获取湿度 } if ($reader->name == 'yweather:forecast') { $weekinfo[$reader->getAttribute('day')] = array($reader->getAttribute('low'), $reader->getAttribute('high'), $reader->getAttribute('code')); } } $reader->close(); $weatherinfo = $this->code2char($code); //".$wind."Km/h $article[0] = array('Title' => "[今天] 岘港 " . $weatherinfo[0] . " " . $temp . "℃", 'Description' => "[今天] 白天: 夜间:\n[明天] 白天: 夜间:", 'PicUrl' => 'http://b2b.gzl.com.cn/Administrator/UploadFile/Editor/Image/2011/10/20111024142542174.jpg', 'Url' => $this->create_loginurl('show_weather')); if (!empty($weekinfo)) { $week_cn = array('Thu' => '星期四', 'Fri' => '星期五', 'Sat' => '星期六', 'Sun' => '星期日', 'Mon' => '星期一', 'Tue' => '星期二', 'Wed' => '星期三'); $i = 1; foreach ($weekinfo as $key => $value) { $week_info = array(); $week_info = $this->code2char($value[2] - 1); $article[$i++] = array('Title' => $week_cn[$key] . " " . $week_info[0] . "\n最高:" . $value[1] . "℃ 最低:" . $value[0] . "℃", 'Description' => "岘港天气", 'PicUrl' => $week_info[1], 'Url' => $this->create_loginurl('show_weather')); } } $this->news($article); }
private function initCountries() { $reader = new XMLReader(); $reader->open(self::XMLPATH); $countries = array(); while ($reader->read()) { if ($reader->name != "iso_3166_entry") { continue; } $country = array(); while ($reader->moveToNextAttribute()) { $country[$reader->name] = $reader->value; } if (array_key_exists('alpha_2_code', $country)) { $countries[$country['alpha_2_code']] = $country; } } $reader->close(); self::$countries = $countries; }
private function getWeatherData($unit) { if ($this->city != "") { $additionalParameter = ""; if ($unit == "c") { $additionalParameter .= "&units=metric"; } $url = $this->basicUrl . $this->city . $this->fixUrlParameter . $additionalParameter; //OCP\Util::writeLog('ocDashboard',"openweather xml url: ".$url, \OCP\Util::DEBUG); $reader = new XMLReader(); $reader->open($url); $data = array(); while ($reader->read()) { if ($reader->nodeType == XMLReader::ELEMENT) { if (isset($this->xmlNodeAttributes[$reader->name])) { $n = 0; while (isset($data[$n][$reader->name])) { $n++; } foreach ($this->xmlNodeAttributes[$reader->name] as $key) { $data[$n][$reader->name][$key] = $reader->getAttribute($key); } if (in_array($reader->name, $this->xmlAddUnit)) { $data[$n][$reader->name]['unit'] = $this->getUnit($reader->name, $unit); } } else { if (isset($this->xmlNodeValueKeys[$reader->name])) { $data[$reader->name] = $reader->readInnerXml(); } } } } $reader->close(); if (count($data) > 0) { $this->weatherData = $data; } else { OCP\Util::writeLog('ocDashboard', "openweather - could not fetch data for " . $this->city, \OCP\Util::ERROR); $this->errorMsg = $this->l->t("Could not fetch data for \"%s\".<br>Please try another value.<br><a href='%s'>» settings</a>", array($this->city, \OCP\Util::linkToRoute('settings_personal'))); } } }
public static function generateVersionInfo($filename) { static $info; if ($info) { return $info; } $r = new \XMLReader(); if (!$r->open($filename)) { throw new \Exception("Could not open file for accessing version information: {$filename}"); } $versions = array(); while ($r->read()) { if ($r->moveToAttribute("name") && ($funcname = str_replace(array("::", "->", "__", "_", '$'), array("-", "-", "-", "-", ""), $r->value)) && $r->moveToAttribute("from") && ($from = $r->value)) { $versions[strtolower($funcname)] = $from; $r->moveToElement(); } } $r->close(); $info = $versions; return $versions; }
/** * 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(); }
public function eginewsAction() { $this->_helper->layout->disableLayout(); $itemcount = 0; $news = array(); $xmlnews = new XMLReader(); $xmlnews->open("http://www.egi.eu/about/news/news.rss"); $parseNode = false; while ($xmlnews->read() && $itemcount <= 5) { if ($xmlnews->name == "item" && $xmlnews->nodeType == XMLReader::ELEMENT) { $itemcount++; $new = array(); $parseNode = true; } elseif ($xmlnews->name == "item" && $xmlnews->nodeType == XMLReader::END_ELEMENT) { $news[] = $new; $parseNode = false; } elseif ($xmlnews->name == "title" && $xmlnews->nodeType == XMLReader::ELEMENT && $parseNode) { $xmlnews->read(); $new["title"] = $xmlnews->value; } elseif ($xmlnews->name == "link" && $xmlnews->nodeType == XMLReader::ELEMENT && $parseNode) { $xmlnews->read(); $new["link"] = $xmlnews->value; } elseif ($xmlnews->name == "pubDate" && $xmlnews->nodeType == XMLReader::ELEMENT && $parseNode) { $xmlnews->read(); $new["date"] = $xmlnews->value; } elseif ($xmlnews->name == "description" && $xmlnews->nodeType == XMLReader::ELEMENT && $parseNode) { $xmlnews->read(); $new["desc"] = $xmlnews->value; } elseif ($xmlnews->localName == "creator" && $xmlnews->nodeType == XMLReader::ELEMENT && $parseNode) { $xmlnews->read(); $new["creator"] = $xmlnews->value; } } $xmlnews->close(); $this->view->news = $news; }
<?php /* $Id$ */ $filename = dirname(__FILE__) . '/_004.xml'; $xmlstring = '<?xml version="1.0" encoding="UTF-8"?> <books><book num="1" idx="2">book1</book></books>'; file_put_contents($filename, $xmlstring); $reader = new XMLReader(); if (!$reader->open($filename)) { exit; } while ($reader->read()) { if ($reader->nodeType != XMLREADER::END_ELEMENT) { echo $reader->name . "\n"; if ($reader->nodeType == XMLREADER::ELEMENT && $reader->hasAttributes) { $attr = $reader->moveToFirstAttribute(); while ($attr) { echo " Attribute Name: " . $reader->name . "\n"; echo " Attribute Value: " . $reader->value . "\n"; $attr = $reader->moveToNextAttribute(); } } } } $reader->close(); unlink($filename); ?> ===DONE===
/** * Get a list of offers to be added or remove. Write the offers to the database. * @param boolean $archive * @param string &$log * @param array &$count_arr * @return null|int|array * @throws Exception */ private function GetOffersPartial($archive, &$log, &$count_arr) { Errors::LogSynchroStep('WebServiceVirgo - GetOffersPartial() start...'); if (!$this->WS()) { Errors::LogSynchroStep('WebServiceVirgo - NO WEBSERVICE'); return null; } try { $log .= "archive=" . (int) $archive . "\n"; $time_start = microtime_float(); if ($this->_sid == "") { return; } $params = array('sid' => $this->_sid); if ($archive) { $result = $this->WS()->getSC()->__soapCall("GetOffersArchive", array($params)); $buf = $result->GetOffersArchiveResult->OffersZip; $status = $result->GetOffersArchiveResult->Status; $msg = $result->GetOffersArchiveResult->Message; } else { $result = $this->WS()->getSC()->__soapCall("GetOffers", array($params)); $buf = $result->GetOffersResult->OffersZip; $status = $result->GetOffersResult->Status; $msg = $result->GetOffersResult->Message; } $time_end = microtime_float(); $time = $time_end - $time_start; if ($this->_DEBUG) { echo "SOAP Call execution time: {$time} seconds<br>"; } if ($status != 0) { throw new Exception($msg); } $zip_file = $archive ? self::TMP_ZIP_ARCH_FILE : self::TMP_ZIP_FILE; $f = fopen($zip_file, "w"); fwrite($f, $buf); fclose($f); $time_end2 = microtime_float(); $time = $time_end2 - $time_end; if ($this->_DEBUG) { echo "Save ZIP execution time: {$time} seconds<br>"; } //unzip XML file with offers $contents = ""; $zip = new ZipArchive(); if ($zip->open($zip_file)) { $fp = $zip->getStream('xml.xml'); if (!$fp) { exit("failed reading xml file (" . getcwd() . "), probably invalid permissions to folder\n"); } $contents = ''; while (!feof($fp)) { $contents .= fread($fp, 1024); } fclose($fp); $zip->close(); $xml_file = $archive ? self::TMP_XML_OFE_ARCH_FILE : self::TMP_XML_OFE_FILE; file_put_contents($xml_file, $contents); if (file_exists($zip_file)) { unlink($zip_file); } } $time_end3 = microtime_float(); $time = $time_end3 - $time_end2; if ($this->_DEBUG) { echo "Save XML execution time: {$time} seconds<br>"; } $times = array("read_props" => 0, "save" => 0, "del_props" => 0, "rooms" => 0, "del_offers" => 0, "rooms_del" => 0, "photos" => 0); $prevOfferId = "0"; $content = file_get_contents($xml_file); //$content = preg_replace("/<UwagiOpis>([^\<\>]*)\<\/UwagiOpis>/m", "<UwagiOpis><![CDATA[$1]]></UwagiOpis>", $content); //$content = preg_replace("/<UwagiNieruchomosc>([^\<\>]*)\<\/UwagiNieruchomosc>/m", "<UwagiNieruchomosc><![CDATA[$1]]></UwagiNieruchomosc>", $content); $fp = fopen($xml_file, 'w'); fwrite($fp, $content); fclose($fp); //open and read XML file $xml2 = new XMLReader(); $xml2->open($xml_file); $domdoc = new DOMDocument(); $ids_do_usuniecia_dodania = array(); $all_agents_ids = array(); $all_dept_ids = array(); $blokuj_agentow = true; $blokuj_oddzialy = true; $time_end4 = microtime_float(); $time = $time_end4 - $time_end3; if ($this->_DEBUG) { echo "Load XML execution time: {$time} seconds<br>"; } $xml2->read(); while ($xml2->name) { //Departments if ($xml2->name == "Oddzial") { if ($blokuj_oddzialy) { $blokuj_oddzialy = false; } $node = simplexml_import_dom($domdoc->importNode($xml2->expand(), true)); if (count($node) > 0) { $log .= "oddzial=" . $node["ID"] . " - " . $node->Nazwa . "\n"; $dep = new Department($node["ID"], $node->Nazwa, $node->Nazwa2, $node->Adres, $node->Miasto, $node->Kod, $node->Nip, $node->Wojewodztwo, $node->Www, $node->Telefon, $node->Email, $node->Fax, $node->Uwagi, $node->Naglowek, $node->Stopka, $node->PlikLogo, $node->ZdjecieWWW, $node->Subdomena, $node->Firma); array_push($all_dept_ids, (int) $node["ID"]); Departments::AddEditDepartment($dep); echo DataBase::GetDbInstance()->LastError(); } } //Agents if ($xml2->name == "Agent") { if ($blokuj_agentow) { $blokuj_agentow = false; } $node = simplexml_import_dom($domdoc->importNode($xml2->expand(), true)); if (count($node) > 0) { $log .= "agent=" . $node["ID"] . " - " . $node->Nazwa . "\n"; $kod_pracownika = 0; if (is_numeric($node->KodPracownika)) { $kod_pracownika = (int) $node->KodPracownika; } $agent = new Agent($node["ID"], $node->Nazwa, $node->Telefon, $node->Komorka, $node->Email, $node->Oddzial, $node->JabberLogin, $node->NrLicencji, $node->OdpowiedzialnyNazwa, $node->OdpowiedzialnyNrLicencji, $node->Komunikator, $node->PlikFoto, $kod_pracownika, $node->DzialFunkcja); array_push($all_agents_ids, (int) $node["ID"]); Agents::AddEditAgent($agent); echo DataBase::GetDbInstance()->LastError(); } } //Offers if ($xml2->name == "Oferty") { $node = simplexml_import_dom($domdoc->importNode($xml2->expand(), true)); if (count($node) > 0) { foreach ($node->children() as $nodeOferta) { $count_arr["suma"]++; $log .= "oferta=" . $nodeOferta["ID"] . " - " . $nodeOferta["Symbol"] . "\n"; //read major properties $rent = strtolower($nodeOferta["Wynajem"]) == "true" ? 1 : 0; $orig = strtolower($nodeOferta["Pierwotny"]) == "true" ? 1 : 0; $przedmiot = $nodeOferta["Przedmiot"]; if ($przedmiot == "Biurowiec") { $przedmiot = "Obiekt"; } $first_page = strtolower($nodeOferta->PierwszaStrona) == "true" ? 1 : 0; $zamiana = $nodeOferta->Zamiana ? 1 : 0; $loc_as_commune = strtolower($nodeOferta["LokalizacjaJakoGmina"]) == "true" ? 1 : 0; $has_swfs = 0; $has_movs = 0; $has_maps = 0; $has_projs = 0; $has_pans = 0; $has_photos = 0; if (isset($nodeOferta->Zdjecia)) { foreach ($nodeOferta->Zdjecia->children() as $zd) { switch ($zd->typ) { case "Zdjecie": $has_photos = 1; break; case "Rzut": $has_projs = 1; break; case "Mapa": $has_maps = 1; break; case "SWF": $has_swfs = 1; break; case "Filmy": $has_movs = 1; break; case "Panorama": $has_pans = 1; break; } } } $attr_arr = array("Link" => null, "ZeroProwizji" => 0); if (isset($nodeOferta->Atrybuty)) { foreach ($nodeOferta->Atrybuty->children() as $at) { if ($at["opis"] == "Link") { $attr_arr["Link"] = (string) $at; } if ($at["opis"] == "ZeroProwizji") { $attr_arr["ZeroProwizji"] = (string) $at; } } } $offer = new Offer($nodeOferta["Jezyk"], CheckNumeric($nodeOferta["ID"]), $nodeOferta["Status"], $przedmiot, $rent, $nodeOferta["Symbol"], $orig, $nodeOferta["Wojewodztwo"], $nodeOferta["Powiat"], $nodeOferta["Lokalizacja"], $nodeOferta["Dzielnica"], $nodeOferta["Rejon"], $nodeOferta["Ulica"], $nodeOferta["Pietro"], CheckNumeric($nodeOferta["Cena"]), CheckNumeric($nodeOferta["CenaM2"]), $nodeOferta["IloscPokoi"], CheckNumeric($nodeOferta["PowierzchniaCalkowita"]), CheckNumeric($nodeOferta["MapSzerokoscGeogr"]), CheckNumeric($nodeOferta["MapDlugoscGeogr"]), $nodeOferta["TechnologiaBudowlana"], $nodeOferta["MaterialKonstrukcyjny"], $nodeOferta["StanWybudowania"], $nodeOferta["RodzajBudynku"], $nodeOferta["Agent"], $nodeOferta["DataWprowadzenia"], $nodeOferta["DataWprowadzenia"], 0, empty_to_null($nodeOferta->Kraj), $nodeOferta->IloscPieter, $nodeOferta->RokBudowy, empty_to_null($nodeOferta->RodzajDomu), $first_page, empty_to_null($nodeOferta->RodzajObiektu), empty_to_null($nodeOferta->SposobPrzyjecia), $nodeOferta->IloscOdslonWWW, null, empty_to_null($nodeOferta->StatusWlasnosci), empty_to_null($nodeOferta->UmeblowanieLista), $nodeOferta->PowierzchniaDzialki, $zamiana, empty_to_null(html_entity_decode($nodeOferta->UwagiOpis)), empty_to_null(html_entity_decode($nodeOferta->UwagiNieruchomosc)), empty_to_null($attr_arr["Link"]), $attr_arr["ZeroProwizji"], $nodeOferta["DataWaznosci"], $has_swfs, $has_movs, $has_photos, $has_pans, $has_maps, $has_projs, $loc_as_commune); $photosNode = null; $roomsNode = null; $modDate = null; $attributesNode = null; $ts = microtime_float(); //properties that are in offers directly $pomin = OffersHelper::$props_arr; //atributes that are in offers directly $pomin_attr = array("Link", "ZeroProwizji"); //read other properties foreach ($nodeOferta->children() as $propNode) { $pname = $propNode->getName(); if ($pname == "StanPrawnyDom" || $pname == "StanPrawnyGruntu" || $pname == "StanPrawnyLokal" || $pname == "StanPrawnyLokalLista") { $offer->setStanPrawny($propNode); } if (in_array($pname, $pomin) === false) { if ($pname == "Zdjecia") { $photosNode = $propNode; } else { if ($pname == "DataAktualizacji") { $modDate = $propNode; } else { if ($pname == "Pomieszczenia") { $roomsNode = $propNode; } else { if ($pname == "Atrybuty") { $attributesNode = $propNode; $set = array(); foreach ($propNode->children() as $listNode) { if (array_search($listNode['opis'], $pomin_attr) === false) { $set[count($set)] = $listNode['opis'] . "#|#" . $listNode; } } $offer->__set($pname, $set); } else { if ($propNode['iset'] == true) { $set = array(); foreach ($propNode->children() as $listNode) { $set[count($set)] = $listNode; } $offer->__set($pname, $set); } else { $offer->__set($pname, $propNode); } } } } } } } if ($nodeOferta['NrLokalu']) { $offer->__set('NrLokalu', $nodeOferta['NrLokalu']); } $times["read_props"] += microtime_float() - $ts; $ts = microtime_float(); //save offer object to database if ($modDate != null) { $offer->SetModificationDate($modDate); } $ret = Offers::AddEditOffer($offer); if ($ret == "A") { $count_arr["dodane"]++; } else { if ($ret == "E") { $count_arr["zmodyfikowane"]++; } } echo DataBase::GetDbInstance()->LastError(); $times["save"] += microtime_float() - $ts; $ts = microtime_float(); //delete unuse properties from offer $addedProperties = array(); foreach ($nodeOferta->children() as $propNode) { $pname = $propNode->getName(); if ($pname == "StanPrawnyDom" || $pname == "StanPrawnyGruntu" || $pname == "StanPrawnyLokal" || $pname == "StanPrawnyLokalLista") { $pname = "StanPrawny"; } if (in_array($pname, $pomin) === false) { if ($pname != "Zdjecia" && $pname != "Pomieszczenia" && $pname != "Atrybuty" && $pname != "DataAktualizacji" || $propNode['iset'] == true) { $prop = Properties::GetPropertyName($pname); if ($prop != null) { $addedProperties[count($addedProperties)] = $prop->GetID(); } } } } if ($nodeOferta['NrLokalu']) { $addedProperties[] = Properties::GetPropertyName('NrLokalu')->GetID(); } if ($attributesNode != null) { $addedProperties[] = Properties::GetPropertyName($attributesNode->getName())->GetID(); } Offers::DeleteUnUseProperties($offer->GetId(), $offer->GetIdLng(), $addedProperties); $times["del_props"] += microtime_float() - $ts; $ts = microtime_float(); //photos $addedPhotos = array(); if ($photosNode != null) { foreach ($photosNode->children() as $photoNode) { $intro = strtolower($photoNode->intro) == "true" ? 1 : 0; $photo = new OfferPhoto($photoNode['ID'], $offer->GetId(), null, $photoNode->plik, $photoNode->opis, $photoNode->lp, $photoNode->typ, $intro, $photoNode['fotoID'], (string) $photoNode->LinkFilmYouTube, (string) $photoNode->LinkMiniaturkaYouTube); OfferPhotos::AddEditPhoto($photo); echo DataBase::GetDbInstance()->LastError(); $addedPhotos[count($addedPhotos)] = $photo->GetId(); } } OfferPhotos::DeleteUnUsePhotos($offer->GetId(), $addedPhotos, 0); $times["photos"] += microtime_float() - $ts; $ts = microtime_float(); //rooms if ($roomsNode != null) { if ($prevOfferId != $offer->GetId() . "") { OfferRooms::DeleteRooms($offer->GetId(), null); } $times["rooms_del"] += microtime_float() - $ts; foreach ($roomsNode->children() as $roomNode) { $room = new OfferRoom(0, $offer->GetId(), $offer->GetIdLng(), $roomNode['Rodzaj'], $roomNode->Lp, $roomNode->Powierzchnia, $roomNode->Poziom, $roomNode->Typ, CheckNumeric($roomNode->Wysokosc), $roomNode->RodzajKuchni, CheckNumeric($roomNode->Ilosc), $roomNode->Glazura, $roomNode->WidokZOkna, $roomNode->Opis, $roomNode->StanPodlogi, $roomNode->RodzajPomieszczenia); //sets of properties $_floors = array(); if ($roomNode->Podlogi) { foreach ($roomNode->Podlogi->children() as $listNode) { $_floors[count($_floors)] = $listNode; } } $room->SetFloors($_floors); $_windowsExhibition = array(); if ($roomNode->WystawaOkien) { foreach ($roomNode->WystawaOkien->children() as $listNode) { $_windowsExhibition[count($_windowsExhibition)] = $listNode; } } $room->SetWindowsExhibition($_windowsExhibition); $_walls = array(); if ($roomNode->Sciany) { foreach ($roomNode->Sciany->children() as $listNode) { $_walls[count($_walls)] = $listNode; } } $room->SetWalls($_walls); $_equipment = array(); if ($roomNode->Wyposazenie) { foreach ($roomNode->Wyposazenie->children() as $listNode) { $_equipment[count($_equipment)] = $listNode; } } $room->SetEquipment($_equipment); OfferRooms::AddRoom($room); echo DataBase::GetDbInstance()->LastError(); } } $times["rooms"] += microtime_float() - $ts; $prevOfferId = $offer->GetId() . ""; } } } //Deleted offers if ($xml2->name == "Usuniete") { $node = simplexml_import_dom($domdoc->importNode($xml2->expand(), true)); foreach ($node->children() as $doUsuniecia) { array_push($ids_do_usuniecia_dodania, (int) $doUsuniecia["ID"]); } } $xml2->read(); } //Delete redundant departments if (!$blokuj_oddzialy) { Departments::DeleteRedundantDepartments($all_dept_ids); } //Delete redundant agents if (!$blokuj_agentow) { Agents::DeleteRedundantAgents($all_agents_ids); } $ts = microtime_float(); $time_end5 = microtime_float(); $time = $time_end5 - $time_end4; $times["del_offers"] += microtime_float() - $ts; if ($this->_DEBUG) { echo "Saving data to db execution time: {$time} seconds<br>"; var_dump($times); } $xml2->close(); Errors::LogSynchroStep('WebServiceVirgo - GetOffersPartial() done'); return $ids_do_usuniecia_dodania; } catch (Exception $ex) { Errors::LogError("WebServiceVirgo:GetOffers", $ex->getMessage() . "; " . $ex->getTraceAsString()); return 0; } }
/** * Parses through xml and looks for the 'cookie' parameter * @param string $xml the xml to parse through * @return string $sessoin returns the session id */ public function read_cookie_xml($xml = '') { global $CFG, $USER, $COURSE; if (empty($xml)) { if (is_siteadmin($USER->id)) { notice(get_string('adminemptyxml', 'adobeconnect'), $CFG->wwwroot . '/admin/settings.php?section=modsettingadobeconnect'); } else { notice(get_string('emptyxml', 'adobeconnect'), '', $COURSE); } } $session = false; // $accountid = false; $reader = new XMLReader(); $reader->XML($xml, 'UTF-8'); while ($reader->read()) { if (0 == strcmp($reader->name, 'cookie')) { if (1 == $reader->nodeType) { $session = $reader->readString(); } } } $reader->close(); $this->_cookie = $session; return $session; }
/** * 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(); $zip = new ZipArchive(); $zip->open($pFilename); $rels = simplexml_load_string($this->_getFromZipArchive($zip, "_rels/.rels")); //~ http://schemas.openxmlformats.org/package/2006/relationships"); foreach ($rels->Relationship as $rel) { if ($rel["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument") { $dir = dirname($rel["Target"]); $relsWorkbook = simplexml_load_string($this->_getFromZipArchive($zip, "{$dir}/_rels/" . basename($rel["Target"]) . ".rels")); //~ http://schemas.openxmlformats.org/package/2006/relationships"); $relsWorkbook->registerXPathNamespace("rel", "http://schemas.openxmlformats.org/package/2006/relationships"); $worksheets = array(); foreach ($relsWorkbook->Relationship as $ele) { if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet") { $worksheets[(string) $ele["Id"]] = $ele["Target"]; } } $xmlWorkbook = simplexml_load_string($this->_getFromZipArchive($zip, "{$rel['Target']}")); //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"); if ($xmlWorkbook->sheets) { $dir = dirname($rel["Target"]); foreach ($xmlWorkbook->sheets->sheet as $eleSheet) { $tmpInfo = array('worksheetName' => (string) $eleSheet["name"], 'lastColumnLetter' => 'A', 'lastColumnIndex' => 0, 'totalRows' => 0, 'totalColumns' => 0); $fileWorksheet = $worksheets[(string) self::array_item($eleSheet->attributes("http://schemas.openxmlformats.org/officeDocument/2006/relationships"), "id")]; $xml = new XMLReader(); $res = $xml->open('zip://' . PHPExcel_Shared_File::realpath($pFilename) . '#' . "{$dir}/{$fileWorksheet}"); $xml->setParserProperty(2, true); $currCells = 0; while ($xml->read()) { if ($xml->name == 'row' && $xml->nodeType == XMLReader::ELEMENT) { $row = $xml->getAttribute('r'); $tmpInfo['totalRows'] = $row; $tmpInfo['totalColumns'] = max($tmpInfo['totalColumns'], $currCells); $currCells = 0; } elseif ($xml->name == 'c' && $xml->nodeType == XMLReader::ELEMENT) { $currCells++; } } $tmpInfo['totalColumns'] = max($tmpInfo['totalColumns'], $currCells); $xml->close(); $tmpInfo['lastColumnIndex'] = $tmpInfo['totalColumns'] - 1; $tmpInfo['lastColumnLetter'] = PHPExcel_Cell::stringFromColumnIndex($tmpInfo['lastColumnIndex']); $worksheetInfo[] = $tmpInfo; } } } } $zip->close(); return $worksheetInfo; }
/** * Parse XML content and convert it to PHP array * * @return void */ private function parseXML() { $xml = new XMLReader(); $headers = array(); $data = array(); $typevar = ''; $varname = ''; $varvalue = ''; $countvar = 0; $itemname = ''; $xml->XML($this->getXMLContent(), 'UTF8'); while ($xml->read()) { if ($xml->name == 'sgc' && $xml->nodeType == XMLReader::ELEMENT) { $headers['version'] = $xml->getAttribute('version'); $headers['scopename'] = $xml->getAttribute('scopename'); while ($xml->read()) { if ($xml->name == 'headers' && $xml->nodeType == XMLReader::ELEMENT) { while ($xml->read()) { if ($xml->name == 'datatype' && $xml->nodeType == XMLReader::ELEMENT) { $headers['datatype'] = $xml->getAttribute('type'); } if ($xml->name == 'component' && $xml->nodeType == XMLReader::ELEMENT) { $xml->read(); if ($xml->hasValue) { $headers['component'] = $xml->value; } else { $headers['component'] = ''; } } if ($xml->name == 'description' && $xml->nodeType == XMLReader::ELEMENT) { $xml->read(); if ($xml->hasValue) { $headers['description'] = $xml->value; } else { $headers['description'] = ''; } break; } } } if ($xml->name == 'envelope' && $xml->nodeType == XMLReader::ELEMENT) { while ($xml->read()) { if ($xml->name == 'datas' && $xml->nodeType == XMLReader::ELEMENT) { while ($xml->read()) { if ($xml->name == 'data' && $xml->nodeType == XMLReader::ELEMENT) { $typevar = $xml->getAttribute('type'); $isnull = $xml->getAttribute('isnull'); while ($xml->read()) { if ($xml->name == $typevar && $xml->nodeType == XMLReader::ELEMENT) { switch ($typevar) { case 'array': $varname = $xml->getAttribute('name'); $countvar = $xml->getAttribute('count'); $i = 0; $data[$varname] = array(); while ($xml->read()) { if ($xml->name == 'items' && $xml->nodeType == XMLReader::ELEMENT) { while ($xml->read()) { if ($xml->name == 'item' && $xml->nodeType == XMLReader::ELEMENT) { $itemname = $xml->getAttribute('name'); $xml->read(); if ($xml->hasValue) { $varvalue = $xml->value; } else { $varvalue = ''; } $data[$varname][$itemname] = $varvalue; if ($i != $countvar - 1) { $i++; } else { break; } } } break; } } break; case 'string': $varname = $xml->getAttribute('name'); $xml->read(); if ($xml->hasValue) { $varvalue = $xml->value; } else { $varvalue = ''; } $data[$varname] = $varvalue; break; } break; } } } } } } } } } } $xml->close(); $this->setData($data); $this->setHeaders($headers); }
/** * Reads the configuration file and creates the class attributes * */ protected function initialize() { $reader = new XMLReader(); $reader->open(parent::getConfigFilePath()); $reader->setRelaxNGSchemaSource(self::WURFL_CONF_SCHEMA); libxml_use_internal_errors(TRUE); while ($reader->read()) { if (!$reader->isValid()) { throw new Exception(libxml_get_last_error()->message); } $name = $reader->name; switch ($reader->nodeType) { case XMLReader::ELEMENT: $this->_handleStartElement($name); break; case XMLReader::TEXT: $this->_handleTextElement($reader->value); break; case XMLReader::END_ELEMENT: $this->_handleEndElement($name); break; } } $reader->close(); if (isset($this->cache["dir"])) { $this->logDir = $this->cache["dir"]; } }