RobertP Posted August 12, 2012 Share Posted August 12, 2012 i am working on a method that will parse an simplexml to an array if you notice any thing odd or incorrect please let me know private function parseResponse(SimpleXMLElement $response){ $parsedResponse = array(); if(method_exists($response,'attributes')){ $parsedResponse['attributes'] = array(); foreach($response->attributes() as $key => $value) $parsedResponse['attributes'][lcfirst((string)$key)] = (string)$value; } if($response->count()>0){ foreach($response->children() as $value) $parsedResponse[] = $this->parseResponse($value); } return $parsedResponse; } Quote Link to comment https://forums.phpfreaks.com/topic/266969-simplexmlelement-to-array/ Share on other sites More sharing options...
requinix Posted August 12, 2012 Share Posted August 12, 2012 i am working on a method that will parse an simplexml to an array Why? Because you don't know how to use a SimpleXMLElement object? Quote Link to comment https://forums.phpfreaks.com/topic/266969-simplexmlelement-to-array/#findComment-1368734 Share on other sites More sharing options...
ignace Posted August 12, 2012 Share Posted August 12, 2012 PEAR has a handy class for that XML_Unserializer http://pear.php.net/manual/en/package.xml.xml-serializer.xml-unserializer.getunserializeddata.php Or the Serializer component from Symfony components. https://github.com/symfony/serializer Quote Link to comment https://forums.phpfreaks.com/topic/266969-simplexmlelement-to-array/#findComment-1368748 Share on other sites More sharing options...
RobertP Posted August 13, 2012 Author Share Posted August 13, 2012 i am creating an api that connects to various xmlrcp servers that i use often. my api will replace a large section of my website network. updated version: private function parseResponse($response,&$parsedResponse = array()){ foreach($response->children() as $elementName => $node){ $nextIdx = count($parsedResponse); $parsedResponse[$nextIdx] = array(); $parsedResponse[$nextIdx]['@name'] = (string)$elementName; if(count($node->attributes())>0){ $parsedResponse[$nextIdx]['@attributes'] = array(); foreach($node->attributes() as $attributeName => $attributeValue) $parsedResponse[$nextIdx]['@attributes'][trim((string)$attributeName)] = trim((string)$attributeValue); } $text = trim((string)$node); if(strlen($text)>0) $parsedResponse[$nextIdx]['@text'] = $text; if($node->count()>0){ $parsedResponse[$nextIdx]['@children'] = array(); $this->parseResponse($node,$parsedResponse[$nextIdx]['@children']); } } return $parsedResponse; } Quote Link to comment https://forums.phpfreaks.com/topic/266969-simplexmlelement-to-array/#findComment-1368886 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.