/** * Parse csv file for getting its metadata * @param \SimpleXMLIterator $data data * @return multitype:Ambigous <> */ public function parseFile($data) { try { $temp = (array) $data; $fileName = $temp['fileName']; $dataType = $temp['dataType']; $duplicateHandle = $data['duplicateHandle']; $fileStorageId = (string) $temp['fileStorageId']; $fullPath = (string) $temp['fullPath']; // count file $fp = file($fullPath); $count = count($fp) - 1; // Get headers $header = array(); if (($handle = fopen($fullPath, "r")) !== false) { // no row length limit plus csv escape with ' while (($csvRow = fgetcsv($handle, 0, ",", "'")) !== false) { for ($columnNo = 0, $columnCount = count($csvRow); $columnNo < $columnCount; $columnNo++) { $header[] = $csvRow[$columnNo]; $data->headers->addChild($columnNo, (string) $csvRow[$columnNo]); } break; } fclose($handle); } $data->records = $count; $file = $data->addChild('file'); $file->addChild('fileName', (string) $temp['fileName']); $file->addChild('fileStorageId', $fileStorageId); unset($data->fileStorageId); unset($data->fileName); unset($data->fullPath); $response = $this->edit($data); // Make response $response['fileName'] = $fileName; $response['headers'] = $header; return $response; } catch (\Exception $e) { echo $e->getMessage(); } }
/** * save and edit system template document * @param unknown $data data * @return Ambigous <multitype:, multitype:Ambigous <boolean, \Base\Model\Service\Ambigous, multitype:, string, unknown, object> NULL > */ public function edit($data) { if (isset($data->id) && !empty($data->id) && isset($data->generatedOn)) { unset($data->recipient); } $result = parent::edit($data); $response = new \SimpleXMLIterator('<?xml version="1.0" encoding="UTF-8"?><template/>'); $response->addChild('id', (string) $result['id']); $response->addChild('fields', 'recipient'); $recipients = $this->getOne($response); $result['recipients'] = $recipients['fields']; return $result; }
function get_elements_from_supplied_file($file) { $found_elements = array(); if ($xml = file_get_contents($file)) { //print_r($xml); //SimpleXMLIterator just runs over the xml and returns the elements found in this file. I think this is just top level //which is what I want. //echo $xml; /* Some safety against XML Injection attack * see: http://phpsecurity.readthedocs.org/en/latest/Injection-Attacks.html * * Attempt a quickie detection of DOCTYPE - discard if it is present (cos it shouldn't be!) */ $collapsedXML = preg_replace("/[[:space:]]/", '', $xml); //echo $collapsedXML; if (preg_match("/<!DOCTYPE/i", $collapsedXML)) { //throw new InvalidArgumentException( // 'Invalid XML: Detected use of illegal DOCTYPE' // ); //echo "fail"; return FALSE; } $loadEntities = libxml_disable_entity_loader(true); $dom = new DOMDocument(); $dom->loadXML($xml); foreach ($dom->childNodes as $child) { if ($child->nodeType === XML_DOCUMENT_TYPE_NODE) { throw new Exception\ValueException('Invalid XML: Detected use of illegal DOCTYPE'); libxml_disable_entity_loader($loadEntities); return FALSE; } } libxml_disable_entity_loader($loadEntities); //Iterate over elements now if (simplexml_import_dom($dom)) { $xmlIterator = new SimpleXMLIterator($xml); for ($xmlIterator->rewind(); $xmlIterator->valid(); $xmlIterator->next()) { foreach ($xmlIterator->getChildren() as $name => $data) { //echo "The $name is '$data' from the class " . get_class($data) . "\n"; $found_elements[] = $name; } } } else { return FALSE; } } return $found_elements; }
/** * Recursively convert \SimpleXMLIterator to array * * @param \SimpleXMLIterator $XMLNode * * @return array */ private static function _XMLNodeToArray($XMLNode) { $result = array(); $attributes = $XMLNode->attributes(); foreach ($attributes as $k => $v) { $val = (string) $v; if ($val == "True" || $val == "False") { $val = (bool) $val; } $result[$k] = $val; } $children = $XMLNode->children(); foreach ($children as $chK => $chNode) { $result['Items'][] = self::_XMLNodeToArray($chNode); } return $result; }
public function asXML($filename = null) { if (!$this->_iso()) return $filename ? parent::asXML($filename) : parent::asXML(); $xml = @parent::asXML(); $xml = utf8_decode($xml); if ($filename) file_put_contents($filename, $xml); return $xml; }
/** * Helper method to retrieve simplexml attributes * @param string $ns * @param boolean $is_prefix * @return array */ function attributes($ns = null, $is_prefix = null) { $attr = (array) parent::attributes($ns, $is_prefix); if (isset($attr['@attributes'])) { return $attr['@attributes']; } return []; }
private function xmlToArray(\SimpleXMLIterator $sxi) { $a = array(); for ($sxi->rewind(); $sxi->valid(); $sxi->next()) { $t = array(); $current = $sxi->current(); $attributes = $current->attributes(); $name = isset($attributes->_key) ? strval($attributes->_key) : $sxi->key(); // save attributes foreach ($attributes as $att_key => $att_value) { if ($att_key !== '_key') { $t[$att_key] = strval($att_value); } } // we parse nodes if ($sxi->hasChildren()) { // children $t = array_merge($t, $this->xmlToArray($current)); } else { // it's a leaf if (empty($t)) { $t = strval($current); // strval will call _toString() } else { $t['_value'] = strval($current); // strval will call _toString() } } $a[$name] = $t; } return $a; }
/** * get files to be uploaded * @param object \SimpleXMLIterator $data data * @return array */ public function getFormUploadFields($data) { $data = new \SimpleXMLIterator($data->asXML()); if (isset($data->values->values->formId)) { $object = new \stdClass(); $object->id = $data->values->values->formId; $object->fields = array('xmlDefinition'); $res = $this->getOne($object); $formXml = file_get_contents('/var/www/htdocs/uploads/' . $res['fields']['xmlDefinition']); $formXml = new \SimpleXMLIterator($formXml); $uploadsFields = $formXml->xpath('//input[@type="file"]'); foreach ($uploadsFields as $field) { $controlName = (string) $field['name']; $control = $data->xpath('//' . $controlName); $fieldAnswers[] = array('fieldName' => $controlName, 'value' => (string) $control[0]); } return array('fields' => $fieldAnswers); } else { return false; } }
protected function execute(InputInterface $input, OutputInterface $output) { $fileInfo = new \SplFileInfo($this->getContainer()->getParameter('kernel.root_dir') . '/../web/sitemap.xml'); if ($fileInfo->isFile() && $fileInfo->isReadable()) { $output->write('Reading sitemap.xml...'); $file = $fileInfo->openFile(); $xml = ''; while (!$file->eof()) { $xml .= $file->fgets(); } $output->writeln(' done.'); $output->write('Updating sitemap.xml...'); $sitemap = new \SimpleXMLIterator($xml); $sitemap->rewind(); $lastmodDate = new \DateTime(); $lastmodDate->sub(new \DateInterval('P1D')); $lastmodDateFormatted = $lastmodDate->format('Y-m-d'); while ($sitemap->valid()) { $sitemap->current()->lastmod = $lastmodDateFormatted; $sitemap->next(); } $file = $file->openFile('w'); $file->fwrite($sitemap->asXML()); $output->writeln(' done.'); } else { $output->writeln('Error: Cannot open file web/sitemap.xml'); } }
/** * Create the ResultSet * * @param object $result * @return void */ public function __construct($result) { $xmlIterator = new \SimpleXMLIterator($result); for ($xmlIterator->rewind(); $xmlIterator->valid(); $xmlIterator->next()) { $temp = new \stdClass(); foreach ($xmlIterator->getChildren()->attributes() as $name => $value) { switch ($name) { case 'orderId': case 'brokerTicketId': case 'quantity': case 'purchaseOrderId': $temp->{$name} = (int) $value; break; case 'cost': $temp->{$name} = (double) $value; break; case 'electronicDelivery': $temp->{$name} = (bool) $value; break; default: $temp->{$name} = (string) $value; } } $this->_results[] = $temp; } unset($xmlIterator, $temp, $name, $value); }
/** * unserialize() * * Create a structure in the object $profile from the structure specficied * in the xml string provided * * @param string xml data * @param Zend_Tool_Project_Profile The profile to use as the top node * @return Zend_Tool_Project_Profile */ public function unserialize($data, Zend_Tool_Project_Profile $profile) { if ($data == null) { throw new Exception('contents not available to unserialize.'); } $this->_profile = $profile; $xmlDataIterator = new SimpleXMLIterator($data); if ($xmlDataIterator->getName() != 'extensionProfile') { throw new Exception('Extension profile must start with a extensionProfile node'); } if (isset($xmlDataIterator['type'])) { $this->_profile->setAttribute('type', (string) $xmlDataIterator['type']); } if (isset($xmlDataIterator['version'])) { $this->_profile->setAttribute('version', (string) $xmlDataIterator['version']); } // start un-serialization of the xml doc $this->_unserializeRecurser($xmlDataIterator); // contexts should be initialized after the unwinding of the profile structure $this->_lazyLoadContexts(); return $this->_profile; }
<pre> <?php $xml = <<<XML <books> <book> <title>PHP Basics</title> <author>Jim Smith</author> </book> <book>XML basics</book> </books> XML; $xmlIterator = new SimpleXMLIterator($xml); //books for ($xmlIterator->rewind(); $xmlIterator->valid(); $xmlIterator->next()) { foreach ($xmlIterator->getChildren() as $name => $data) { echo "The {$name} is '{$data}' from the class " . get_class($data) . "\n"; } echo $xmlIterator->getName() . "\n"; //2 times of books will be print out } ?> </pre>
if (!$res) { unlink(COOKIE_FILE); die("Cannot log in to BGZ!" . PHP_EOL); } if (!$quiet) { printf("Done." . PHP_EOL . "Getting cash import file list ... "); } $files = get_files(); if (!$files) { unlink(COOKIE_FILE); die("Cannot get file list!" . PHP_EOL); } if (!$quiet) { printf("Done." . PHP_EOL); } $xml = new SimpleXMLIterator($files); $xml->rewind(); while ($xml->valid()) { if ($xml->key() == "rows") { $rows = $xml->getChildren(); $rows->rewind(); while ($rows->valid()) { if ($rows->key() == "row") { $fileid = $filename = NULL; $props = $rows->getChildren(); $props->rewind(); while ($props->valid()) { switch ($props->key()) { case "id": $fileid = strval($props->current()); break;
protected function parseDependencyType(\SimpleXMLIterator $iterator, DependencyCollection $dependencies, $required = true) { $iterator->rewind(); while ($iterator->valid()) { $elt = $iterator->current(); $name = $elt->getName(); $iterator->next(); if ($name === 'php') { $dependencies->import($this->parsePhpCondition($elt)); } elseif ($name === 'pearinstaller') { // Let's just ignore this for now! } else { // TODO do not ignore recommended, nodefault and uri, providesextension $identifier = 'pear2://' . (string) $elt->channel . '/' . (string) $elt->name; $dependencies[] = new Dependency($identifier, isset($elt->min) ? (string) $elt->min : null, isset($elt->max) ? (string) $elt->max : null, isset($elt->conflicts) ? Dependency::CONFLICT : ($required ? Dependency::REQUIRED : Dependency::OPTIONAL)); foreach ($elt->exclude as $exclude) { $dependencies[] = new Dependency($identifier, (string) $exclude, (string) $exclude, Dependency::CONFLICT); } } } }
<?php /** * Created by PhpStorm. * User: Administrator * Date: 2015/12/1 * Time: 11:29 */ $it = new SimpleXMLIterator(file_get_contents('test.xml')); foreach ($it as $key => $node) { echo $key . "<br/>"; if ($it->hasChildren()) { foreach ($it->getChildren() as $element => $value) { echo "\t" . $element . " : " . $value . "<br/>"; } } }
/** * _unserializeRecurser() * * This method will be used to traverse the depths of the structure * as needed to *unserialize* the profile from an xmlIterator * * @param SimpleXMLIterator $xmlIterator * @param Zend_Tool_Project_Profile_Resource $resource */ protected function _unserializeRecurser(SimpleXMLIterator $xmlIterator, Zend_Tool_Project_Profile_Resource $resource = null) { foreach ($xmlIterator as $resourceName => $resourceData) { $contextName = $resourceName; $subResource = new Zend_Tool_Project_Profile_Resource($contextName); $subResource->setProfile($this->_profile); if ($resourceAttributes = $resourceData->attributes()) { $attributes = array(); foreach ($resourceAttributes as $attrName => $attrValue) { $attributes[$attrName] = (string) $attrValue; } $subResource->setAttributes($attributes); } if ($resource) { $resource->append($subResource, false); } else { $this->_profile->append($subResource); } if ($this->_contextRepository->isOverwritableContext($contextName) == false) { $subResource->initializeContext(); } if ($xmlIterator->hasChildren()) { self::_unserializeRecurser($xmlIterator->getChildren(), $subResource); } } }
private function ParseXML($data_content) { $xmlIterator = new SimpleXMLIterator($data_content); $xmlIterator->rewind(); $xmlIterator->next(); while ($xmlIterator->current() != Null) { $current = $xmlIterator->current(); $Item = $this->ParsePerItem($current); $Parsed[$Item["sku"]] = $Item; $xmlIterator->next(); } return $Parsed; }
/** * Gets the current XML node as a true string. * * @return string The current XML node as a true string. */ public function to_string() { $s = parent::__toString(); if ($this->attributes()) { return json_decode(substr($s, 14)); } return $s; }
/** * Converts a SimpleXMLIterator structure into an associative array. * * Used to parse an XML response from Mollom servers into a PHP array. For * example: * @code * $elements = new SimpleXmlIterator($response_body); * $parsed_response = $this->parseXML($elements); * @endcode * * @param SimpleXMLIterator $sxi * A SimpleXMLIterator structure of the server response body. * * @return array * An associative, possibly multidimensional array. */ public static function parseXML(SimpleXMLIterator $sxi) { $a = array(); $remove = array(); for ($sxi->rewind(); $sxi->valid(); $sxi->next()) { $key = $sxi->key(); // Recurse into non-scalar values. if ($sxi->hasChildren()) { $value = self::parseXML($sxi->current()); } else { $value = strval($sxi->current()); } if (!isset($a[$key])) { $a[$key] = $value; } else { // First time we reach here, convert the existing keyed item. Do not // remove $key, so we enter this path again. if (!isset($remove[$key])) { $a[] = $a[$key]; // Mark $key for removal. $remove[$key] = $key; } // Add the new item. $a[] = $value; } } // Lastly, remove named keys that have been converted to indexed keys. foreach ($remove as $key) { unset($a[$key]); } return $a; }
function count() { echo __METHOD__ . "\n"; return parent::count(); }
/** * Converts SimpleXMLIterator object into an array. * @param SimpleXMLIterator $xmlIterator * @return string[] */ public function simplexmlToArray($xmlIterator) { $xmlStringArray = array(); for ($xmlIterator->rewind(); $xmlIterator->valid(); $xmlIterator->next()) { if ($xmlIterator->hasChildren()) { $object = $xmlIterator->current(); $xmlStringArray[$object->getName()] = $this->simplexmlToArray($object); } else { $object = $xmlIterator->current(); $xmlStringArray[$object->getName()] = (string) $xmlIterator->current(); } } return $xmlStringArray; }
protected function _unserializeRecurser(SimpleXMLIterator $projectProfileIterator, Zend_Tool_Provider_ZfProject_ProjectContext_ProjectContextAbstract $context = null) { foreach ($projectProfileIterator as $projectProfileNodeName => $projectProfileNode) { $subContextClass = self::getContextByName($projectProfileNodeName); $subContext = new $subContextClass(); if ($subContext->getContextName() === 'projectProfileFile') { $subContext->setProjectProfile($this); } if ($attributes = $projectProfileNode->attributes()) { foreach ($attributes as $attrName => $attrValue) { $clnAttrs[$attrName] = (string) $attrValue; } $subContext->setParameters($clnAttrs); } if ($context) { $context->append($subContext); } else { $this->appendProjectContext($subContext); } if ($projectProfileIterator->hasChildren()) { self::_unserializeRecurser($projectProfileIterator->getChildren(), $subContext); } } }
/** * @param \SimpleXMLIterator $sxi * * @param string $tableName * @param string $xpath */ protected function processValueOnly(\SimpleXMLIterator $sxi, string $tableName, string $xpath = '//result/child::*[not(*|@*|self::dataTime)]') { $items = $sxi->xpath($xpath); if (false === $items || 0 === count($items)) { return; } /** * @var \SimpleXMLElement[] $items */ $columns = []; foreach ($items as $ele) { $name = (string) $ele->getName(); $columns[$name] = $this->inferTypeFromName($name, true); } uksort($columns, function ($alpha, $beta) { return strtolower($alpha) <=> strtolower($beta); }); $this->tables[$tableName] = ['values' => $columns]; }
/** * @param \SimpleXMLIterator $element * @param \Twig_Template $template * * @param string $formId * @param string $xPath * @param string $requiredChildren * @param array $identityRefs * * @return array|bool */ public function getChildrenValues($element, $template, $formId, $xPath = "", $requiredChildren = "", $identityRefs = array()) { $retArr = array(); $targetAttributes = array('key', 'iskey', 'mandatory'); foreach ($element as $label => $el) { $attributesArr = array_fill_keys($targetAttributes, false); foreach ($element->attributes() as $name => $attr) { if ($name == "key") { $attributesArr[$name] = (string) $attr[0]; } } foreach ($el->attributes() as $name => $attr) { if (in_array($name, array('iskey', 'mandatory'))) { $attributesArr[$name] = (string) $attr[0]; } } if (($attributesArr['iskey'] !== "true" && $attributesArr['key'] == false || $requiredChildren !== "" && $label != $requiredChildren) && $attributesArr['mandatory'] == false) { continue; } if ($attributesArr['key'] !== false) { $requiredChildren = $attributesArr['key']; } else { $requiredChildren = ""; } $twigArr = array(); $twigArr['key'] = ""; $twigArr['xpath'] = ""; $twigArr['element'] = $el; $twigArr['useHiddenInput'] = true; $twigArr['moduleIdentityRefs'] = $identityRefs; $newXPath = $xPath . "/*"; $res = $this->getAvailableLabelValuesForXPath($formId, $newXPath); $retArr[$label] = array(); if (isset($res['labelsAttributes'][$label])) { $retArr[$label]['labelAttributes'] = $res['labelsAttributes'][$label]; } $retArr[$label]['valueElem'] = $this->removeMultipleWhitespaces($template->renderBlock('configInputElem', $twigArr)); $retArr[$label]['children'] = $this->getChildrenValues($el, $template, $formId, $newXPath, $requiredChildren); } return sizeof($retArr) ? $retArr : false; }
<pre> <?php $xmlIterator = new SimpleXMLIterator('<books><book>PHP basics</book><book>XML basics</book></books>'); var_dump($xmlIterator->current()); $xmlIterator->rewind(); // rewind to first element var_dump($xmlIterator->current()); /** * NULL object(SimpleXMLIterator)#2 (0) { } */ ?> </pre>
/** * Create an Array from XML * * This method sets up the SimpleXMLIterator and starts the parsing * of an xml body to iterate through it and transform it into * an array that can be used by the developers. * * @param string $xml * @return array An array mapped to the passed xml */ public static function arrayFromXml($xml) { // replace namespace defs $xml = str_replace('xmlns=', 'ns=', $xml); // catch libxml errors libxml_use_internal_errors(true); try { $iterator = new SimpleXMLIterator($xml); } catch(Exception $e) { $xmlErrors = libxml_get_errors(); return new Frapi_Exception( 'Xml Parsing Failed', 'INVALID_XML', 400, 'xml_parsing' ); libxml_clear_errors(); } $xmlRoot = $iterator->getName(); $type = $iterator->attributes()->type; // SimpleXML provides the root information on construct self::$_xmlRoot = $iterator->getName(); self::$_responseType = $type; // return the mapped array with the root element as the header return array($xmlRoot => self::_iteratorToArray($iterator)); }
/** * Convert XML iterator to array * * @static * @param \SimpleXMLIterator $xml * @param null $ns * @return array */ public static function xmlToArray(\SimpleXMLIterator $xml, $ns = null) { $a = []; for ($xml->rewind(); $xml->valid(); $xml->next()) { $key = $xml->key(); if (!isset($a[$key])) { $a[$key] = []; } foreach ($xml->current()->attributes() as $k => $v) { $a[$key][self::INDEX_ATTRIBUTES][$k] = (string) $v; } if ($ns) { foreach ($ns as $name) { foreach ($xml->current()->attributes($name) as $k => $v) { $a[$key][self::INDEX_ATTRIBUTES][$k] = (string) $v; } } } if ($xml->hasChildren()) { $a[$key][self::INDEX_CONTENT] = self::xmlToArray($xml->current(), $ns); } else { $a[$key][self::INDEX_CONTENT] = strval($xml->current()); } } return $a; }
protected function _unserializeRecurser(SimpleXMLIterator $xmlIterator, Zend_Tool_Project_Structure_Node $node = null) { foreach ($xmlIterator as $nodeName => $nodeData) { $context = Zend_Tool_Project_Structure_Context_Registry::getInstance()->getContext($nodeName); $subNode = new Zend_Tool_Project_Structure_Node($context); if ($attributes = $nodeData->attributes()) { foreach ($attributes as $attrName => $attrValue) { $method = 'set' . $attrName; if (method_exists($subNode, $method)) { $subNode->{$method}((string) $attrValue); } elseif (method_exists($context, $method)) { $context->{$method}((string) $attrValue); } } } if (method_exists($context, 'setGraph')) { $context->setGraph($this->_graph); } if ($node) { $node->append($subNode); } else { $this->_graph->append($subNode); } if ($xmlIterator->hasChildren()) { self::_unserializeRecurser($xmlIterator->getChildren(), $subNode); } } }
function testHasChildrenDuringIteration() { $s = new SimpleXMLIterator(basicXML()); echo "first level nodes have children: "; foreach ($s as $i => $e) { echo "{$i}: ", $s->hasChildren() ? 'yes' : 'no', ", "; } echo "\n"; }
/** * sets up the SimpleXMLIterator and starts the parsing * @access public * @param string $xml * @return array array mapped to the passed xml */ public static function arrayFromXml($xml) { // SimpleXML provides the root information on construct $iterator = new SimpleXMLIterator($xml); $xmlRoot = Braintree_Util::delimiterToCamelCase($iterator->getName()); $type = $iterator->attributes()->type; self::$_xmlRoot = $iterator->getName(); self::$_responseType = $type; // return the mapped array with the root element as the header return array($xmlRoot => self::_iteratorToArray($iterator)); }