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; }
/** * _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); } } }
/** * 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; }
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); } } }
/** * 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; }
<?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/>"; } } }
function hasChildren() { echo __METHOD__ . "\n"; return parent::hasChildren(); }
<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); for ($xmlIterator->rewind(); $xmlIterator->valid(); $xmlIterator->next()) { if ($xmlIterator->hasChildren()) { var_dump($xmlIterator->current()); } } ?> </pre>
// $nXmlSectionKey switch ($xmlSetupIterator->key()) { case 'special_char': // Log special characters $strDescription = '-- special characters "' . $xmlSetupIterator->current() . '"' . PHP_EOL; $strLine = ''; logLog(0, $strDescription, $strLine, $nLogModeSetupXml); break; case 'parameter': // Log parameters // $strDescription = '-- parameter "' . $xmlSetupIterator->current() . '"' . PHP_EOL; // $strLine = ''; // logLog(0, $strDescription, $strLine, 2); break; default: if (!$xmlSetupIterator->hasChildren()) { // XML-setup error, no exit if (2 > $nbXmlSetupError) { $nbXmlSetupError = 1; } // Empty XML-setup section $strDescription = '## Empty XML-setup section "' . $xmlSetupIterator->key() . '" ##' . PHP_EOL; $strLine = ''; logError(0, $strDescription, $strLine, $nLogModeSetupXml); if ('' !== trim($xmlSetupIterator->current())) { // Empty XML-setup section, element value $strDescription = '## Empty XML-setup section, element value "' . trim($xmlSetupIterator->current()) . '" ##' . PHP_EOL; $strLine = ''; logError(0, $strDescription, $strLine, $nLogModeSetupXml); } } else {
/** * @param SimpleXMLIterator $sxi */ public function sxiToArray($sxi) { $a = array(); for ($sxi->rewind(); $sxi->valid(); $sxi->next()) { if (!array_key_exists($sxi->key(), $a)) { $a[$sxi->key()] = array(); } if ($sxi->hasChildren()) { $a[$sxi->key()]['children'] = $this->sxiToArray($sxi->current()); } else { $a[$sxi->key()][] = strval($sxi->current()); } } return $a; }
var_dump($xml->asXML()); /* string(181) "<?xml version="1.0"?> <application name="ls"> <param long="list">l</param> <param>a</param> <help> <cmd>h</cmd> </help> <new-node>1</new-node> </application> */ //---------- $iterator = new SimpleXMLIterator($string); foreach ($iterator as $key => $value) { echo "key: {$key}, value: {$value}\n"; if ($iterator->hasChildren()) { var_dump($iterator->current()); } } /* key: param, value: l key: param, value: a key: help, value: object(SimpleXMLIterator)#5 (1) { ["cmd"]=> string(1) "h" } */
*/ try { $xmlString = file_get_contents('spl.xml'); $simpleIt = new SimpleXMLIterator($xmlString); // 循环所有的节点 foreach (new RecursiveIteratorIterator($simpleIt, 1) as $name => $data) { //echo $name, '=>', $data, "<br />"; } // while 循环 $simpleIt->rewind(); while ($simpleIt->valid()) { /*var_dump($simpleIt->key()); echo '=>'; var_dump($simpleIt->current());*/ // getChildren() 获得当前节点的子节点 if ($simpleIt->hasChildren()) { //var_dump($simpleIt->getChildren()); } $simpleIt->next(); } // xpath 可以通过path直接获得指定节点的值 var_dump($simpleIt->xpath('animal/category/species')); } catch (Exception $e) { echo $e->getMessage(); } echo '--------------------------------- SimpleXMLIterator END-----------------------------------', '<br />'; echo '--------------------------------- CachingIterator START-----------------------------------', '<br />'; /** * CachingIterator 提前读取一个元素 * 可以用于确定当前元素是否为最后一个元素 */
/** * 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"; }