/** * Converts a SimpleXMLElement object into an array recurrsively. * * @param \SimpleXMLElement $xmlObject the object to convert * @return array the converted object */ protected function _xmlToArray($xmlObject) { // Setup $result = array(); if(count($xmlObject->children())) { foreach($xmlObject->children() as $key => $value) { if($value->children()) { $value = $this->_xmlToArray($value); } else { $value = (string) $value; } if(array_key_exists($key, $result)) { if(!is_array($result[$key]) || !array_key_exists(0, $result[$key])) { $result[$key] = array($result[$key]); } $result[$key][] = $value; } else { $result[$key] = $value; } } } elseif(!isset($xmlObject['extends'])) { $result = (string) $xmlObject; } return $result; }
public static function parse($content) { $arr = array(); $xml = new \SimpleXMLElement($content); $sml = $xml->children(XMLNamespace::SML_NAMESPACE); if ($sml != null) { $arr['uuid'] = $sml->identification->IdentifierList->identifier->Term->value; $gml = $xml->children(XMLNamespace::GML_NAMESPACE); $timePeriod = $sml->validTime->children(XMLNamespace::GML_NAMESPACE)->TimePeriod; $arr['startDate'] = SensorMLParser::parseSmlDate($timePeriod->beginPosition, true); $arr['endDate'] = SensorMLParser::parseSmlDate($timePeriod->endPosition, false); $arr['name'] = trim($gml->name); $arr['desc'] = trim($gml->description); $smlComponents = $sml->components; if ($smlComponents != null) { $comps = $smlComponents->ComponentList; $arr['components'] = array(); foreach ($comps->component as $component) { $childRef = $component->attributes(XMLNamespace::XLINK_NAMESPACE)->href; $arr['components'][] = array('name' => trim($component->attributes()->name), 'ref' => $childRef, 'uuid' => basename($childRef, ".xml")); } } } return $arr; }
/** * * @param SimpleXMLElement $xmlElement */ public function read(SimpleXMLElement $xmlElement) { if ($xmlElement->children()) { $this->read($xmlElement->children()); } $this->xmlArray[] = $xmlElement; }
/** * Proceeds the import. * * @throws Recipe_Exception_Generic * @return Recipe_Language_XML_Importer */ public function proceed() { if (is_null($this->xml)) { throw new Recipe_Exception_Generic("No XML data set."); } $defaultLang = false; /* @var XMLObj $lang */ foreach ($this->xml->children() as $lang) { if ($lang->getAttribute("action") == "setDefault") { $defaultLang = $lang->getName(); } $createData = array("langcode" => $lang->getName(), "title" => $lang->getAttribute("title")); $this->getFromLangCode($lang->getName(), $createData); /* @var XMLObj $group */ foreach ($lang->getChildren() as $group) { $this->getFromGroupName($group->getName()); $this->importData = array(); /* @var XMLObj $phrase */ foreach ($group->getChildren() as $phrase) { $this->importData[$phrase->getName()] = $phrase->getString(); } $this->import(); } } if ($defaultLang) { $this->setDefaultLanguage($defaultLang); } return $this; }
public function parseAndGetValues() { $count = $this->xml->children()->count(); if ($count > 0) { $this->parseXMLData($this->xml); } return $this->getPreparedValues(); }
public function parse() { $this->simpleXml = new \SimpleXMLElement(file_get_contents($this->file)); $content = $this->simpleXml->children(); foreach ($content->character as $character) { $this->parseCharacter($character); } return $this->dictionary; }
/** * @return ElggXMLElement[] Child elements */ public function getChildren() { $children = $this->_element->children(); $result = array(); foreach ($children as $val) { $result[] = new ElggXMLElement($val); } return $result; }
/** * Generates table from simpleXMLElement object. * * @param $name * @param null $simpleXmlElement */ public function __construct($name, \SimpleXMLElement $simpleXmlElement = null) { $this->setElementName($name); if ($simpleXmlElement) { $this->setColHeadings((array) $simpleXmlElement->children()->colHeading); foreach ($simpleXmlElement->children()->row as $row) { $this->addRow((array) $row->col); } } }
/** * {@inheritdoc} */ public function getNodes($name) { $nodes = []; foreach ($this->data->children() as $kNode => $node) { if ($kNode != $name) { continue; } $nodes[] = new XmlFileNode([$kNode], $node); } return $nodes; }
/** * Check whether element has children * * @param \SimpleXMLElement $element * @return bool */ public function hasChildren(\SimpleXMLElement $element) { if (!$element->children()) { return false; } // simplexml bug: @attributes is in children() but invisible in foreach foreach ($element->children() as $child) { return true; } return false; }
private function doPrettyPrintXML(SimpleXMLElement $han, $prefix = "") { if (count($han->children()) < 1) { return $prefix . "<" . $han->getName() . $this->doWarpAttributes($han->attributes()) . ">" . $han . "</" . $han->getName() . "><br />"; } $ret = $prefix . "<" . $han->getName() . $this->doWarpAttributes($han->attributes()) . "><br />"; foreach ($han->children() as $key => $child) { $ret .= $this->doPrettyPrintXML($child, $prefix . " "); } $ret .= $prefix . "</" . $han->getName() . "><br />"; return $ret; }
public function __construct($xmlString = '') { $this->xml = simplexml_load_string($xmlString); if (!empty($xmlString)) { foreach ($this->xml->children() as $name => $data) { if ($this->hasProperty($name)) { $this->{$name} = trim($data); } } } parent::__construct(); }
/** * Parses and returns the value inside the specified XML element. * * @param SimpleXMLElement $containerXml * @return mixed */ public static function parseValueInside($containerXml) { $dictValue = $containerXml->children(Splunk_AtomFeed::NS_S)->dict; $listValue = $containerXml->children(Splunk_AtomFeed::NS_S)->list; if (Splunk_XmlUtil::elementExists($dictValue)) { return Splunk_AtomFeed::parseDict($dictValue); } else { if (Splunk_XmlUtil::elementExists($listValue)) { return Splunk_AtomFeed::parseList($listValue); } else { return Splunk_XmlUtil::getTextContent($containerXml); } } }
/** * Lookup the DOI from the crossref site */ function _lookupdoi($doi) { // Get the API key from the config file $apikey = $this->config->item('easydeposit_crossrefdoilookup_apikey'); // Check the DOI is in the correct format (strip any http prefix) $doi = str_replace('http://dx.doi.org/', '', $doi); if (strpos($doi, '10.') !== 0 || strlen($doi) < 4) { $this->form_validation->set_message('_lookupdoi', 'Bad DOI'); return FALSE; } // Get the DOI, throw an error if we can't connect if (!($response = file_get_contents('http://www.crossref.org/openurl/?id=doi:' . $doi . '&noredirect=true&format=unixref&pid=' . $apikey))) { $this->form_validation->set_message('_lookupdoi', 'Error connecting to CrossRef'); return FALSE; } // An example of a response, useful if developing or debugging offline //$response = '<doi_records xmlns="http://www.crossref.org/xschema/1.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.crossref.org/xschema/1.1 http://www.crossref.org/schema/unixref1.1.xsd http://www.crossref.org/xschema/1.0 http://www.crossref.org/schema/unixref1.0.xsd"><doi_record xmlns="http://www.crossref.org/xschema/1.0" owner="10.1108" timestamp="2009-10-10 07:01:10.0"><crossref><journal><journal_metadata language="en"><full_title>Program: electronic library and information systems</full_title><abbrev_title>Program: electronic library and information systems</abbrev_title><issn media_type="print">0033-0337</issn></journal_metadata><journal_issue><publication_date media_type="print"><year>2009</year></publication_date><journal_volume><volume>43</volume></journal_volume><issue>4</issue></journal_issue><journal_article publication_type="full_text"><titles><title>If SWORD is the answer, what is the question?: Use of the Simple Web-service Offering Repository Deposit protocol</title></titles><contributors><person_name sequence="first" contributor_role="author"><given_name>Stuart</given_name><surname>Lewis</surname></person_name><person_name sequence="additional" contributor_role="author"><given_name>Leonie</given_name><surname>Hayes</surname></person_name><person_name sequence="additional" contributor_role="author"><given_name>Vanessa</given_name><surname>Newton-Wade</surname></person_name><person_name sequence="additional" contributor_role="author"><given_name>Antony</given_name><surname>Corfield</surname></person_name><person_name sequence="additional" contributor_role="author"><given_name>Richard</given_name><surname>Davis</surname></person_name><person_name sequence="additional" contributor_role="author"><given_name>Tim</given_name><surname>Donohue</surname></person_name><person_name sequence="additional" contributor_role="author"><given_name>Scott</given_name><surname>Wilson</surname></person_name></contributors><publication_date media_type="print"><year>2009</year></publication_date><pages><first_page>407</first_page><last_page>418</last_page></pages><doi_data><doi>10.1108/00330330910998057</doi><resource>http://www.emeraldinsight.com/10.1108/00330330910998057</resource></doi_data><citation_list/></journal_article></journal></crossref></doi_record></doi_records>'; // Parse and process the xml $xml = new SimpleXMLElement($response); $error = $xml->children()->doi_record->crossref->error; if (!empty($error)) { $this->form_validation->set_message('_lookupdoi', $error); return FALSE; } // Looks like we have a match, so process it $record = $xml->children()->doi_record->crossref->journal; $_SESSION['crossrefdoi-title'] = $record->journal_article->titles->title . ''; $contributors = $record->journal_article->contributors; $authorcount = 0; foreach ($contributors->person_name as $contributor) { $_SESSION['crossrefdoi-author' . ++$authorcount] = $contributor->surname . ', ' . $contributor->given_name; } $_SESSION['crossrefdoi-authorcount'] = $authorcount; $_SESSION['crossrefdoi-year'] = $record->journal_article->publication_date->year . ''; $_SESSION['crossrefdoi-journaltitle'] = $record->journal_metadata->full_title . ''; $pstart = $record->journal_article->pages->first_page; $pend = $record->journal_article->pages->last_page; $pages = ''; if (!empty($pstart)) { $pages = $pstart; if (!empty($pend)) { $pages .= '-' . $pend; } } $_SESSION['crossrefdoi-volume'] = $record->journal_issue->journal_volume->volume . ''; $_SESSION['crossrefdoi-issue'] = $record->journal_issue->issue . ''; return TRUE; }
public function itCreatesAnXMLEntryForEachPlanningShortAccess() { $exporter = new AgileDashboard_XMLExporter($this->xml_validator, $this->planning_permissions_manager); $exporter->export($this->xml_tree, $this->plannings); $this->assertEqual(1, count($this->xml_tree->children())); $agiledashborad = AgileDashboard_XMLExporter::NODE_AGILEDASHBOARD; $plannings = AgileDashboard_XMLExporter::NODE_PLANNINGS; foreach ($this->xml_tree->{$agiledashborad}->children() as $plannings_node) { $this->assertEqual(2, count($plannings_node->children())); $this->assertEqual($plannings_node->getName(), $plannings); } foreach ($this->xml_tree->{$agiledashborad}->{$plannings}->children() as $planning) { $this->assertEqual($planning->getName(), AgileDashboard_XMLExporter::NODE_PLANNING); $this->assertEqual(1, count($planning->children())); } }
public function xmlToArray($object, &$array = array()) { if (is_string($object)) { $object = new \SimpleXMLElement($object); } $children = $object->children(); $executed = false; foreach ($children as $elementName => $node) { if (isset($array[$elementName]) && $array[$elementName] !== null) { if (isset($array[$elementName][0]) && $array[$elementName][0] !== null) { $i = count($array[$elementName]); $this->xmlToArray($node, $array[$elementName][$i]); } else { $tmp = $array[$elementName]; $array[$elementName] = array(); $array[$elementName][0] = $tmp; $i = count($array[$elementName]); $this->xmlToArray($node, $array[$elementName][$i]); } } else { $array[$elementName] = array(); $this->xmlToArray($node, $array[$elementName]); } $executed = true; } if (!$executed && !$children->getName()) { $array = (string) $object; } return $array; }
/** * Convert an XML document to a multi dimensional array * Pass in an XML document (or SimpleXMLElement object) and this recrusively loops through and builds a representative array * * @param string $xml - XML document - can optionally be a SimpleXMLElement object * @return array ARRAY */ public static function toArray($xml) { if (is_string($xml)) { $xml = new SimpleXMLElement($xml); } $children = $xml->children(); if (!$children) { return (string) $xml; } $arr = array(); foreach ($children as $key => $node) { $node = ArrayToXML::toArray($node); // support for 'anon' non-associative arrays if ($key == 'anon') { $key = count($arr); } // if the node is already set, put it into an array if (isset($arr[$key])) { if (!is_array($arr[$key]) || !isset($arr[$key][0])) { $arr[$key] = array($arr[$key]); } $arr[$key][] = $node; } else { $arr[$key] = $node; } } return $arr; }
function getImportantActs($xml_url, $xsl_filename, $n_nodes) { try { // read the xml from url $xmldoc = new DomDocument(); $xmldoc->load($xml_url); // read xslt file $xsldoc = new DomDocument(); $xsldoc->load($xsl_filename); $xsl = new XSLTProcessor(); $xsl->importStyleSheet($xsldoc); // trasforma XML secondo l'XSLT ed estrae il contenuto del div $transformed_xml = new SimpleXMLElement($xsl->transformToXML($xmldoc)); $nodes = $transformed_xml->children(); // write values to screen $cnt = 0; foreach ($nodes as $node) { $cnt++; $atto = OppAttoPeer::retrieveByPK($node['atto_id']); printf("\t%d. %s => %f\n", $cnt, $atto->getTitoloCompleto(), $node['totale']); if ($cnt >= $n_nodes) { break; } } } catch (Exception $e) { printf("Errore durante la scrittura del file: %s\n", $e->getMessage()); } }
/** * Set remote content * * @param SimpleXMLElement $xml * @return void */ private function setRemoteContent(\SimpleXMLElement $xml) { $this->remoteContent = new \Doctrine\Common\Collections\ArrayCollection(); foreach ($xml->children() as $remoteContentXml) { $this->remoteContent->add(RemoteContent::createFromXml($remoteContentXml)); } }
/** * Unserialize SimpleXMLElement * * @param \SimpleXMLElement $element Element to unserialize * @param string $classHint Hint to which class unserialize * * @return mixed unserialized object */ protected function unserializeXml(\SimpleXMLElement $element, $classHint = null) { if ($this->configValue("extractClassFrom", "tagName") == "tagName") { $elementClassHint = $element->getName(); } else { $xsiAttrs = $element->attributes("http://www.w3.org/2001/XMLSchema-instance"); if (!isset($xsiAttrs["type"])) { throw new \Exception("Element {$element->getName()} has no {http://www.w3.org/2001/XMLSchema-instance}type attribute"); } $elementClassHint = $xsiAttrs["type"]; } $mapperClass = $this->configValue("mapperClasses", []); if (isset($mapperClass[$elementClassHint])) { $className = $mapperClass[$elementClassHint]; } else { $className = $classHint ? $classHint : rtrim($this->configValue("classesNamespace", ""), '\\') . '\\' . $elementClassHint; } if (!class_exists($className, true)) { throw new ClassNotFoundException("Class '{$className}' not found"); } $classInstance = new $className(); $this->checkNodes($element->attributes(), $className, $classInstance); $this->checkNodes($element->children(), $className, $classInstance); return $classInstance; }
public function load($inputFile) { $objects = array(); if (!file_exists($inputFile)) { KalturaLog::err("input file " . $inputFile . " not found"); exit(1); } $inputXml = file_get_contents($inputFile); $xml = new SimpleXMLElement($inputXml); foreach ($xml->children() as $searchableObject) { $objectAttribtues = $searchableObject->attributes(); $objName = $objectAttribtues["name"]; $this->parseObject("{$objName}", $objectAttribtues); $this->searchableIndices["{$objName}"] = array(); foreach ($searchableObject->children() as $type => $searchableField) { switch ($type) { case "field": $this->parseField("{$objName}", $searchableField); break; case "index": $this->parseIndex("{$objName}", $searchableField); break; } } $objects[] = "{$objName}"; } return $objects; }
/** * Converts SimpleXMLElement to multidimensional array * @param SimpleXMLElement $xml SimpleXMLElement to convert * @return array * @throws Exception */ private function simpleXMLToArray($xml) { $ObjectNodes = array('error', 'money', 'any_originator', 'version', 'originator'); if (!$xml instanceof \SimpleXMLElement) { throw new \Exception(__METHOD__ . ' - Параметр $xml должен иметь тип SimpleXMLElement'); } $result = (object) null; $value = trim((string) $xml); if (!empty($value)) { $result->value = $value; } foreach ($xml->children() as $elementName => $child) { if (in_array($elementName, $ObjectNodes)) { if ($child->count || $child->attributes->count) { $result->{$elementName} = $this->simpleXMLToArray($child); } else { $result->{$elementName} = trim((string) $child); } } else { $result->{$elementName}[] = $this->simpleXMLToArray($child); } } foreach ($xml->attributes() as $attr_name => $value) { $result->{$attr_name} = trim($value); } return $result; }
/** * Returns array representation of XML data, starting from a node pointed by * $node variable. * * Please see the documentation of this class for details about the internal * representation of XML data. * * @param \SimpleXMLElement $node A node to start parsing from * @return mixed An array representing parsed XML node or string value if leaf */ protected function parseNode(\SimpleXMLElement $node) { $parsedNode = []; if ($node->count() === 0) { return (string) $node; } foreach ($node->children() as $child) { $nameOfChild = $child->getName(); $parsedChild = $this->parseNode($child); if (count($child->attributes()) > 0) { $parsedAttributes = ''; foreach ($child->attributes() as $attributeName => $attributeValue) { if ($this->isDistinguishingAttribute($attributeName)) { $parsedAttributes .= '[@' . $attributeName . '="' . $attributeValue . '"]'; } } $nameOfChild .= $parsedAttributes; } if (!isset($parsedNode[$nameOfChild])) { // We accept only first child when they are non distinguishable (i.e. they differs only by non-distinguishing attributes) $parsedNode[$nameOfChild] = $parsedChild; } } return $parsedNode; }
public function _xml_to_array($xml) { $iter = 0; $arr = array(); if (is_string($xml)) { $xml = new SimpleXMLElement($xml); } if (!$xml instanceof SimpleXMLElement) { return $arr; } $has_children = false; foreach ($xml->children() as $element) { $has_children = true; $elementName = $element->getName(); if ($element->children()) { $arr[$elementName][] = $this->_xml_to_array($element, $namespaces); } else { $shouldCreateArray = array_key_exists($elementName, $arr) && !is_array($arr[$elementName]); if ($shouldCreateArray) { $arr[$elementName] = array($arr[$elementName]); } $shouldAddValueToArray = array_key_exists($elementName, $arr) && is_array($arr[$elementName]); if ($shouldAddValueToArray) { $arr[$elementName][] = trim($element[0]); } else { $arr[$elementName] = trim($element[0]); } } $iter++; } if (!$has_children) { $arr['_contents'] = trim($xml[0]); } return $arr; }
private function parseXml(SimpleXMLElement $xml, PiBX_AST_Tree $ast, $parentObject) { $count = $ast->countChildren(); if (!$xml->children()) { // a leaf node in the XML documents doesn't need to be parsed any further return (string) $xml; } if ($count == 0) { if ($ast instanceof PiBX_AST_Structure) { $newObject = $this->parseStructure($xml, $ast, $parentObject); } else { throw new RuntimeException('Not supported yet'); } } else { $newObject = $parentObject; for ($i = 0; $i < $count; $i++) { $child = $ast->get($i); $name = $child->getName(); $childXml = $xml->{$name}; if ($child instanceof PiBX_AST_Structure) { $newObject = $this->parseStructure($xml->{$name}, $child, $parentObject); } elseif ($child instanceof PiBX_AST_Collection) { $name = $ast->getName(); $list = $this->parseCollection($xml, $child, $parentObject); $setter = $child->getSetMethod(); $parentObject->{$setter}($list); } elseif ($child instanceof PiBX_AST_TypeAttribute) { $newObject = $this->parseTypeAttribute($xml, $child, $parentObject); } else { throw new RuntimeException('Not supported yet'); } } } return $newObject; }
/** * Decode a application/hal+xml document into a Nocarrier\Hal object. * * @param Hal $hal * @param $data * @param int $depth * * @throws \RuntimeException * @static * @access public * @return \Nocarrier\Hal */ public static function fromXml(Hal $hal, $data, $depth = 0) { if (!$data instanceof \SimpleXMLElement) { try { $data = new \SimpleXMLElement($data); } catch (\Exception $e) { throw new \RuntimeException('The $data parameter must be valid XML'); } } $children = $data->children(); $links = clone $children->link; unset($children->link); $embedded = clone $children->resource; unset($children->resource); $hal->setUri((string) $data->attributes()->href); $hal->setData((array) $children); foreach ($links as $links) { if (!is_array($links)) { $links = array($links); } foreach ($links as $link) { list($rel, $href, $attributes) = self::extractKnownData($link); $hal->addLink($rel, $href, $attributes); } } if ($depth > 0) { foreach ($embedded as $embed) { list($rel, $href, $attributes) = self::extractKnownData($embed); $hal->addResource($rel, self::fromXml($embed, $depth - 1)); } } $hal->setShouldStripAttributes(false); return $hal; }
public static function parse($content) { $arr = array(); $xml = new \SimpleXMLElement($content); $sos = $xml->children(XMLNamespace::SOS_NAMESPACE); if ($sos != null) { $obs = $sos->observation; $omObs = $obs->children(XMLNamespace::OM_NAMESPACE)->OM_Observation; $gml = $omObs->children(XMLNamespace::GML_NAMESPACE); $desc = $gml->description; $name = $gml->name; $uuidI = null; foreach ($gml->identifier as $identifier) { if ($identifier->attributes()->codeSpace == 'uuid') { $uuidI = (string) $identifier; } } $observation = new ObservationModel(); $arr['uuid'] = $uuidI; $arr['name'] = trim($name); $arr['description'] = trim($desc); $childRef = $omObs->procedure->attributes(XMLNamespace::XLINK_NAMESPACE)->href; $arr['system-uuid'] = basename($childRef, ".xml"); $childRef = $omObs->result->attributes(XMLNamespace::XLINK_NAMESPACE)->href; $arr['result-file'] = basename($childRef, ""); } return $arr; }
/** * @param \SimpleXMLElement $xml */ protected function update($xml) { $this->name = (string) $xml['name']; foreach ($xml->children() as $element) { $this->values[] = $this->createElement($element, $this->youtrack); } }
/** * Рекурсивная функция обработки входных параметров api.xml * * @param SimpleXMLElement $input Элемент дерева api.xml * @param Array $options_input Опции функции * @return Array */ public function _proccess_options_input(SimpleXMLElement $input, array &$options_input = array()) { foreach ($input->children() as $node) { $name = (string) $node->attributes()->{'name'}; switch ($node->getName()) { case 'integer': case 'long': $options_input[$name] = 0; break; case 'double': $options_input[$name] = 0.0; break; case 'ip_address': $options_input[$name] = '0.0.0.0'; break; case 'string': $options_input[$name] = ''; break; case 'if': $this->_proccess_options_input($node, $options_input); break; case 'for': $sibling = $node->xpath('preceding-sibling::*[1]'); if (!isset($sibling[0])) { throw new Exception('Not provided an error, contact the developer (' . __FUNCTION__ . ')'); } $options_input[(string) $sibling[0]->attributes()->{'name'}] = array($this->_proccess_options_input($node)); break; } } return $options_input; }
/** * @param \Spryker\Zed\Oms\Business\Process\ProcessInterface[] $processMap * * @return \Spryker\Zed\Oms\Business\Process\ProcessInterface[] */ protected function createStates(array $processMap) { $stateToProcessMap = []; $xmlProcesses = $this->rootElement->children(); foreach ($xmlProcesses as $xmlProcess) { $processName = $this->getAttributeString($xmlProcess, 'name'); $process = $processMap[$processName]; if (!empty($xmlProcess->states)) { $xmlStates = $xmlProcess->states->children(); /** @var \SimpleXMLElement $xmlState */ foreach ($xmlStates as $xmlState) { $state = clone $this->state; $state->setName($this->getAttributeString($xmlState, 'name')); $state->setDisplay($this->getAttributeString($xmlState, 'display')); $state->setReserved($this->getAttributeBoolean($xmlState, 'reserved')); $state->setProcess($process); if ($xmlState->flag) { $flags = $xmlState->children(); foreach ($flags->flag as $flag) { $state->addFlag((string) $flag); } } $process->addState($state); $stateToProcessMap[$state->getName()] = $process; } } } return $stateToProcessMap; }